// SPDX-License-Identifier: GPL-2.012//! Implementation of the kernel's memory allocation infrastructure.34pub mod allocator;5pub mod kbox;6pub mod kvec;7pub mod layout;89pub use self::kbox::Box;10pub use self::kbox::KBox;11pub use self::kbox::KVBox;12pub use self::kbox::VBox;1314pub use self::kvec::IntoIter;15pub use self::kvec::KVVec;16pub use self::kvec::KVec;17pub use self::kvec::VVec;18pub use self::kvec::Vec;1920/// Indicates an allocation error.21#[derive(Copy, Clone, PartialEq, Eq, Debug)]22pub struct AllocError;2324use crate::error::{code::EINVAL, Result};25use core::{alloc::Layout, ptr::NonNull};2627/// Flags to be used when allocating memory.28///29/// They can be combined with the operators `|`, `&`, and `!`.30///31/// Values can be used from the [`flags`] module.32#[derive(Clone, Copy, PartialEq)]33pub struct Flags(u32);3435impl Flags {36/// Get the raw representation of this flag.37pub(crate) fn as_raw(self) -> u32 {38self.039}4041/// Check whether `flags` is contained in `self`.42pub fn contains(self, flags: Flags) -> bool {43(self & flags) == flags44}45}4647impl core::ops::BitOr for Flags {48type Output = Self;49fn bitor(self, rhs: Self) -> Self::Output {50Self(self.0 | rhs.0)51}52}5354impl core::ops::BitAnd for Flags {55type Output = Self;56fn bitand(self, rhs: Self) -> Self::Output {57Self(self.0 & rhs.0)58}59}6061impl core::ops::Not for Flags {62type Output = Self;63fn not(self) -> Self::Output {64Self(!self.0)65}66}6768/// Allocation flags.69///70/// These are meant to be used in functions that can allocate memory.71pub mod flags {72use super::Flags;7374/// Zeroes out the allocated memory.75///76/// This is normally or'd with other flags.77pub const __GFP_ZERO: Flags = Flags(bindings::__GFP_ZERO);7879/// Allow the allocation to be in high memory.80///81/// Allocations in high memory may not be mapped into the kernel's address space, so this can't82/// be used with `kmalloc` and other similar methods.83///84/// This is normally or'd with other flags.85pub const __GFP_HIGHMEM: Flags = Flags(bindings::__GFP_HIGHMEM);8687/// Users can not sleep and need the allocation to succeed.88///89/// A lower watermark is applied to allow access to "atomic reserves". The current90/// implementation doesn't support NMI and few other strict non-preemptive contexts (e.g.91/// `raw_spin_lock`). The same applies to [`GFP_NOWAIT`].92pub const GFP_ATOMIC: Flags = Flags(bindings::GFP_ATOMIC);9394/// Typical for kernel-internal allocations. The caller requires `ZONE_NORMAL` or a lower zone95/// for direct access but can direct reclaim.96pub const GFP_KERNEL: Flags = Flags(bindings::GFP_KERNEL);9798/// The same as [`GFP_KERNEL`], except the allocation is accounted to kmemcg.99pub const GFP_KERNEL_ACCOUNT: Flags = Flags(bindings::GFP_KERNEL_ACCOUNT);100101/// For kernel allocations that should not stall for direct reclaim, start physical IO or102/// use any filesystem callback. It is very likely to fail to allocate memory, even for very103/// small allocations.104pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT);105106/// Suppresses allocation failure reports.107///108/// This is normally or'd with other flags.109pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN);110}111112/// Non Uniform Memory Access (NUMA) node identifier.113#[derive(Clone, Copy, PartialEq)]114pub struct NumaNode(i32);115116impl NumaNode {117/// Create a new NUMA node identifier (non-negative integer).118///119/// Returns [`EINVAL`] if a negative id or an id exceeding [`bindings::MAX_NUMNODES`] is120/// specified.121pub fn new(node: i32) -> Result<Self> {122// MAX_NUMNODES never exceeds 2**10 because NODES_SHIFT is 0..10.123if node < 0 || node >= bindings::MAX_NUMNODES as i32 {124return Err(EINVAL);125}126Ok(Self(node))127}128}129130/// Specify necessary constant to pass the information to Allocator that the caller doesn't care131/// about the NUMA node to allocate memory from.132impl NumaNode {133/// No node preference.134pub const NO_NODE: NumaNode = NumaNode(bindings::NUMA_NO_NODE);135}136137/// The kernel's [`Allocator`] trait.138///139/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described140/// via [`Layout`].141///142/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on143/// an object instance.144///145/// In order to be able to support `#[derive(CoercePointee)]` later on, we need to avoid a design146/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind147/// of `self` parameter.148///149/// # Safety150///151/// - A memory allocation returned from an allocator must remain valid until it is explicitly freed.152///153/// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`]154/// function of the same type.155///156/// - Implementers must ensure that all trait functions abide by the guarantees documented in the157/// `# Guarantees` sections.158pub unsafe trait Allocator {159/// The minimum alignment satisfied by all allocations from this allocator.160///161/// # Guarantees162///163/// Any pointer allocated by this allocator is guaranteed to be aligned to `MIN_ALIGN` even if164/// the requested layout has a smaller alignment.165const MIN_ALIGN: usize;166167/// Allocate memory based on `layout`, `flags` and `nid`.168///169/// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout170/// constraints (i.e. minimum size and alignment as specified by `layout`).171///172/// This function is equivalent to `realloc` when called with `None`.173///174/// # Guarantees175///176/// When the return value is `Ok(ptr)`, then `ptr` is177/// - valid for reads and writes for `layout.size()` bytes, until it is passed to178/// [`Allocator::free`] or [`Allocator::realloc`],179/// - aligned to `layout.align()`,180///181/// Additionally, `Flags` are honored as documented in182/// <https://docs.kernel.org/core-api/mm-api.html#mm-api-gfp-flags>.183fn alloc(layout: Layout, flags: Flags, nid: NumaNode) -> Result<NonNull<[u8]>, AllocError> {184// SAFETY: Passing `None` to `realloc` is valid by its safety requirements and asks for a185// new memory allocation.186unsafe { Self::realloc(None, layout, Layout::new::<()>(), flags, nid) }187}188189/// Re-allocate an existing memory allocation to satisfy the requested `layout` and190/// a specific NUMA node request to allocate the memory for.191///192/// Systems employing a Non Uniform Memory Access (NUMA) architecture contain collections of193/// hardware resources including processors, memory, and I/O buses, that comprise what is194/// commonly known as a NUMA node.195///196/// `nid` stands for NUMA id, i. e. NUMA node identifier, which is a non-negative integer197/// if a node needs to be specified, or [`NumaNode::NO_NODE`] if the caller doesn't care.198///199/// If the requested size is zero, `realloc` behaves equivalent to `free`.200///201/// If the requested size is larger than the size of the existing allocation, a successful call202/// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but203/// may also be larger.204///205/// If the requested size is smaller than the size of the existing allocation, `realloc` may or206/// may not shrink the buffer; this is implementation specific to the allocator.207///208/// On allocation failure, the existing buffer, if any, remains valid.209///210/// The buffer is represented as `NonNull<[u8]>`.211///212/// # Safety213///214/// - If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation215/// created by this [`Allocator`]; if `old_layout` is zero-sized `p` does not need to be a216/// pointer returned by this [`Allocator`].217/// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and218/// `old_layout` is ignored.219/// - `old_layout` must match the `Layout` the allocation has been created with.220///221/// # Guarantees222///223/// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then224/// it additionally guarantees that:225/// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new226/// and old size, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] ==227/// p[0..min(layout.size(), old_layout.size())]`.228/// - when the return value is `Err(AllocError)`, then `ptr` is still valid.229unsafe fn realloc(230ptr: Option<NonNull<u8>>,231layout: Layout,232old_layout: Layout,233flags: Flags,234nid: NumaNode,235) -> Result<NonNull<[u8]>, AllocError>;236237/// Free an existing memory allocation.238///239/// # Safety240///241/// - `ptr` must point to an existing and valid memory allocation created by this [`Allocator`];242/// if `old_layout` is zero-sized `p` does not need to be a pointer returned by this243/// [`Allocator`].244/// - `layout` must match the `Layout` the allocation has been created with.245/// - The memory allocation at `ptr` must never again be read from or written to.246unsafe fn free(ptr: NonNull<u8>, layout: Layout) {247// SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this248// allocator. We are passing a `Layout` with the smallest possible alignment, so it is249// smaller than or equal to the alignment previously used with this allocation.250let _ = unsafe {251Self::realloc(252Some(ptr),253Layout::new::<()>(),254layout,255Flags(0),256NumaNode::NO_NODE,257)258};259}260}261262/// Returns a properly aligned dangling pointer from the given `layout`.263pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> {264let ptr = layout.align() as *mut u8;265266// SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero.267unsafe { NonNull::new_unchecked(ptr) }268}269270271