// SPDX-License-Identifier: GPL-2.012//! Maple trees.3//!4//! C header: [`include/linux/maple_tree.h`](srctree/include/linux/maple_tree.h)5//!6//! Reference: <https://docs.kernel.org/core-api/maple_tree.html>78use core::{9marker::PhantomData,10ops::{Bound, RangeBounds},11ptr,12};1314use kernel::{15alloc::Flags,16error::to_result,17prelude::*,18types::{ForeignOwnable, Opaque},19};2021/// A maple tree optimized for storing non-overlapping ranges.22///23/// # Invariants24///25/// Each range in the maple tree owns an instance of `T`.26#[pin_data(PinnedDrop)]27#[repr(transparent)]28pub struct MapleTree<T: ForeignOwnable> {29#[pin]30tree: Opaque<bindings::maple_tree>,31_p: PhantomData<T>,32}3334/// A maple tree with `MT_FLAGS_ALLOC_RANGE` set.35///36/// All methods on [`MapleTree`] are also accessible on this type.37#[pin_data]38#[repr(transparent)]39pub struct MapleTreeAlloc<T: ForeignOwnable> {40#[pin]41tree: MapleTree<T>,42}4344// Make MapleTree methods usable on MapleTreeAlloc.45impl<T: ForeignOwnable> core::ops::Deref for MapleTreeAlloc<T> {46type Target = MapleTree<T>;4748#[inline]49fn deref(&self) -> &MapleTree<T> {50&self.tree51}52}5354#[inline]55fn to_maple_range(range: impl RangeBounds<usize>) -> Option<(usize, usize)> {56let first = match range.start_bound() {57Bound::Included(start) => *start,58Bound::Excluded(start) => start.checked_add(1)?,59Bound::Unbounded => 0,60};6162let last = match range.end_bound() {63Bound::Included(end) => *end,64Bound::Excluded(end) => end.checked_sub(1)?,65Bound::Unbounded => usize::MAX,66};6768if last < first {69return None;70}7172Some((first, last))73}7475impl<T: ForeignOwnable> MapleTree<T> {76/// Create a new maple tree.77///78/// The tree will use the regular implementation with a higher branching factor, rather than79/// the allocation tree.80#[inline]81pub fn new() -> impl PinInit<Self> {82pin_init!(MapleTree {83// SAFETY: This initializes a maple tree into a pinned slot. The maple tree will be84// destroyed in Drop before the memory location becomes invalid.85tree <- Opaque::ffi_init(|slot| unsafe { bindings::mt_init_flags(slot, 0) }),86_p: PhantomData,87})88}8990/// Insert the value at the given index.91///92/// # Errors93///94/// If the maple tree already contains a range using the given index, then this call will95/// return an [`InsertErrorKind::Occupied`]. It may also fail if memory allocation fails.96///97/// # Examples98///99/// ```100/// use kernel::maple_tree::{InsertErrorKind, MapleTree};101///102/// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?;103///104/// let ten = KBox::new(10, GFP_KERNEL)?;105/// let twenty = KBox::new(20, GFP_KERNEL)?;106/// let the_answer = KBox::new(42, GFP_KERNEL)?;107///108/// // These calls will succeed.109/// tree.insert(100, ten, GFP_KERNEL)?;110/// tree.insert(101, twenty, GFP_KERNEL)?;111///112/// // This will fail because the index is already in use.113/// assert_eq!(114/// tree.insert(100, the_answer, GFP_KERNEL).unwrap_err().cause,115/// InsertErrorKind::Occupied,116/// );117/// # Ok::<_, Error>(())118/// ```119#[inline]120pub fn insert(&self, index: usize, value: T, gfp: Flags) -> Result<(), InsertError<T>> {121self.insert_range(index..=index, value, gfp)122}123124/// Insert a value to the specified range, failing on overlap.125///126/// This accepts the usual types of Rust ranges using the `..` and `..=` syntax for exclusive127/// and inclusive ranges respectively. The range must not be empty, and must not overlap with128/// any existing range.129///130/// # Errors131///132/// If the maple tree already contains an overlapping range, then this call will return an133/// [`InsertErrorKind::Occupied`]. It may also fail if memory allocation fails or if the134/// requested range is invalid (e.g. empty).135///136/// # Examples137///138/// ```139/// use kernel::maple_tree::{InsertErrorKind, MapleTree};140///141/// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?;142///143/// let ten = KBox::new(10, GFP_KERNEL)?;144/// let twenty = KBox::new(20, GFP_KERNEL)?;145/// let the_answer = KBox::new(42, GFP_KERNEL)?;146/// let hundred = KBox::new(100, GFP_KERNEL)?;147///148/// // Insert the value 10 at the indices 100 to 499.149/// tree.insert_range(100..500, ten, GFP_KERNEL)?;150///151/// // Insert the value 20 at the indices 500 to 1000.152/// tree.insert_range(500..=1000, twenty, GFP_KERNEL)?;153///154/// // This will fail due to overlap with the previous range on index 1000.155/// assert_eq!(156/// tree.insert_range(1000..1200, the_answer, GFP_KERNEL).unwrap_err().cause,157/// InsertErrorKind::Occupied,158/// );159///160/// // When using .. to specify the range, you must be careful to ensure that the range is161/// // non-empty.162/// assert_eq!(163/// tree.insert_range(72..72, hundred, GFP_KERNEL).unwrap_err().cause,164/// InsertErrorKind::InvalidRequest,165/// );166/// # Ok::<_, Error>(())167/// ```168pub fn insert_range<R>(&self, range: R, value: T, gfp: Flags) -> Result<(), InsertError<T>>169where170R: RangeBounds<usize>,171{172let Some((first, last)) = to_maple_range(range) else {173return Err(InsertError {174value,175cause: InsertErrorKind::InvalidRequest,176});177};178179let ptr = T::into_foreign(value);180181// SAFETY: The tree is valid, and we are passing a pointer to an owned instance of `T`.182let res = to_result(unsafe {183bindings::mtree_insert_range(self.tree.get(), first, last, ptr, gfp.as_raw())184});185186if let Err(err) = res {187// SAFETY: As `mtree_insert_range` failed, it is safe to take back ownership.188let value = unsafe { T::from_foreign(ptr) };189190let cause = if err == ENOMEM {191InsertErrorKind::AllocError(kernel::alloc::AllocError)192} else if err == EEXIST {193InsertErrorKind::Occupied194} else {195InsertErrorKind::InvalidRequest196};197Err(InsertError { value, cause })198} else {199Ok(())200}201}202203/// Erase the range containing the given index.204///205/// # Examples206///207/// ```208/// use kernel::maple_tree::MapleTree;209///210/// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?;211///212/// let ten = KBox::new(10, GFP_KERNEL)?;213/// let twenty = KBox::new(20, GFP_KERNEL)?;214///215/// tree.insert_range(100..500, ten, GFP_KERNEL)?;216/// tree.insert(67, twenty, GFP_KERNEL)?;217///218/// assert_eq!(tree.erase(67).map(|v| *v), Some(20));219/// assert_eq!(tree.erase(275).map(|v| *v), Some(10));220///221/// // The previous call erased the entire range, not just index 275.222/// assert!(tree.erase(127).is_none());223/// # Ok::<_, Error>(())224/// ```225#[inline]226pub fn erase(&self, index: usize) -> Option<T> {227// SAFETY: `self.tree` contains a valid maple tree.228let ret = unsafe { bindings::mtree_erase(self.tree.get(), index) };229230// SAFETY: If the pointer is not null, then we took ownership of a valid instance of `T`231// from the tree.232unsafe { T::try_from_foreign(ret) }233}234235/// Lock the internal spinlock.236#[inline]237pub fn lock(&self) -> MapleGuard<'_, T> {238// SAFETY: It's safe to lock the spinlock in a maple tree.239unsafe { bindings::spin_lock(self.ma_lock()) };240241// INVARIANT: We just took the spinlock.242MapleGuard(self)243}244245#[inline]246fn ma_lock(&self) -> *mut bindings::spinlock_t {247// SAFETY: This pointer offset operation stays in-bounds.248let lock_ptr = unsafe { &raw mut (*self.tree.get()).__bindgen_anon_1.ma_lock };249lock_ptr.cast()250}251252/// Free all `T` instances in this tree.253///254/// # Safety255///256/// This frees Rust data referenced by the maple tree without removing it from the maple tree,257/// leaving it in an invalid state. The caller must ensure that this invalid state cannot be258/// observed by the end-user.259unsafe fn free_all_entries(self: Pin<&mut Self>) {260// SAFETY: The caller provides exclusive access to the entire maple tree, so we have261// exclusive access to the entire maple tree despite not holding the lock.262let mut ma_state = unsafe { MaState::new_raw(self.into_ref().get_ref(), 0, usize::MAX) };263264loop {265// This uses the raw accessor because we're destroying pointers without removing them266// from the maple tree, which is only valid because this is the destructor.267let ptr = ma_state.mas_find_raw(usize::MAX);268if ptr.is_null() {269break;270}271// SAFETY: By the type invariants, this pointer references a valid value of type `T`.272// By the safety requirements, it is okay to free it without removing it from the maple273// tree.274drop(unsafe { T::from_foreign(ptr) });275}276}277}278279#[pinned_drop]280impl<T: ForeignOwnable> PinnedDrop for MapleTree<T> {281#[inline]282fn drop(mut self: Pin<&mut Self>) {283// We only iterate the tree if the Rust value has a destructor.284if core::mem::needs_drop::<T>() {285// SAFETY: Other than the below `mtree_destroy` call, the tree will not be accessed286// after this call.287unsafe { self.as_mut().free_all_entries() };288}289290// SAFETY: The tree is valid, and will not be accessed after this call.291unsafe { bindings::mtree_destroy(self.tree.get()) };292}293}294295/// A reference to a [`MapleTree`] that owns the inner lock.296///297/// # Invariants298///299/// This guard owns the inner spinlock.300#[must_use = "if unused, the lock will be immediately unlocked"]301pub struct MapleGuard<'tree, T: ForeignOwnable>(&'tree MapleTree<T>);302303impl<'tree, T: ForeignOwnable> Drop for MapleGuard<'tree, T> {304#[inline]305fn drop(&mut self) {306// SAFETY: By the type invariants, we hold this spinlock.307unsafe { bindings::spin_unlock(self.0.ma_lock()) };308}309}310311impl<'tree, T: ForeignOwnable> MapleGuard<'tree, T> {312/// Create a [`MaState`] protected by this lock guard.313pub fn ma_state(&mut self, first: usize, end: usize) -> MaState<'_, T> {314// SAFETY: The `MaState` borrows this `MapleGuard`, so it can also borrow the `MapleGuard`s315// read/write permissions to the maple tree.316unsafe { MaState::new_raw(self.0, first, end) }317}318319/// Load the value at the given index.320///321/// # Examples322///323/// Read the value while holding the spinlock.324///325/// ```326/// use kernel::maple_tree::MapleTree;327///328/// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?;329///330/// let ten = KBox::new(10, GFP_KERNEL)?;331/// let twenty = KBox::new(20, GFP_KERNEL)?;332/// tree.insert(100, ten, GFP_KERNEL)?;333/// tree.insert(200, twenty, GFP_KERNEL)?;334///335/// let mut lock = tree.lock();336/// assert_eq!(lock.load(100).map(|v| *v), Some(10));337/// assert_eq!(lock.load(200).map(|v| *v), Some(20));338/// assert_eq!(lock.load(300).map(|v| *v), None);339/// # Ok::<_, Error>(())340/// ```341///342/// Increment refcount under the lock, to keep value alive afterwards.343///344/// ```345/// use kernel::maple_tree::MapleTree;346/// use kernel::sync::Arc;347///348/// let tree = KBox::pin_init(MapleTree::<Arc<i32>>::new(), GFP_KERNEL)?;349///350/// let ten = Arc::new(10, GFP_KERNEL)?;351/// let twenty = Arc::new(20, GFP_KERNEL)?;352/// tree.insert(100, ten, GFP_KERNEL)?;353/// tree.insert(200, twenty, GFP_KERNEL)?;354///355/// // Briefly take the lock to increment the refcount.356/// let value = tree.lock().load(100).map(Arc::from);357///358/// // At this point, another thread might remove the value.359/// tree.erase(100);360///361/// // But we can still access it because we took a refcount.362/// assert_eq!(value.map(|v| *v), Some(10));363/// # Ok::<_, Error>(())364/// ```365#[inline]366pub fn load(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {367// SAFETY: `self.tree` contains a valid maple tree.368let ret = unsafe { bindings::mtree_load(self.0.tree.get(), index) };369if ret.is_null() {370return None;371}372373// SAFETY: If the pointer is not null, then it references a valid instance of `T`. It is374// safe to borrow the instance mutably because the signature of this function enforces that375// the mutable borrow is not used after the spinlock is dropped.376Some(unsafe { T::borrow_mut(ret) })377}378}379380impl<T: ForeignOwnable> MapleTreeAlloc<T> {381/// Create a new allocation tree.382pub fn new() -> impl PinInit<Self> {383let tree = pin_init!(MapleTree {384// SAFETY: This initializes a maple tree into a pinned slot. The maple tree will be385// destroyed in Drop before the memory location becomes invalid.386tree <- Opaque::ffi_init(|slot| unsafe {387bindings::mt_init_flags(slot, bindings::MT_FLAGS_ALLOC_RANGE)388}),389_p: PhantomData,390});391392pin_init!(MapleTreeAlloc { tree <- tree })393}394395/// Insert an entry with the given size somewhere in the given range.396///397/// The maple tree will search for a location in the given range where there is space to insert398/// the new range. If there is not enough available space, then an error will be returned.399///400/// The index of the new range is returned.401///402/// # Examples403///404/// ```405/// use kernel::maple_tree::{MapleTreeAlloc, AllocErrorKind};406///407/// let tree = KBox::pin_init(MapleTreeAlloc::<KBox<i32>>::new(), GFP_KERNEL)?;408///409/// let ten = KBox::new(10, GFP_KERNEL)?;410/// let twenty = KBox::new(20, GFP_KERNEL)?;411/// let thirty = KBox::new(30, GFP_KERNEL)?;412/// let hundred = KBox::new(100, GFP_KERNEL)?;413///414/// // Allocate three ranges.415/// let idx1 = tree.alloc_range(100, ten, ..1000, GFP_KERNEL)?;416/// let idx2 = tree.alloc_range(100, twenty, ..1000, GFP_KERNEL)?;417/// let idx3 = tree.alloc_range(100, thirty, ..1000, GFP_KERNEL)?;418///419/// assert_eq!(idx1, 0);420/// assert_eq!(idx2, 100);421/// assert_eq!(idx3, 200);422///423/// // This will fail because the remaining space is too small.424/// assert_eq!(425/// tree.alloc_range(800, hundred, ..1000, GFP_KERNEL).unwrap_err().cause,426/// AllocErrorKind::Busy,427/// );428/// # Ok::<_, Error>(())429/// ```430pub fn alloc_range<R>(431&self,432size: usize,433value: T,434range: R,435gfp: Flags,436) -> Result<usize, AllocError<T>>437where438R: RangeBounds<usize>,439{440let Some((min, max)) = to_maple_range(range) else {441return Err(AllocError {442value,443cause: AllocErrorKind::InvalidRequest,444});445};446447let ptr = T::into_foreign(value);448let mut index = 0;449450// SAFETY: The tree is valid, and we are passing a pointer to an owned instance of `T`.451let res = to_result(unsafe {452bindings::mtree_alloc_range(453self.tree.tree.get(),454&mut index,455ptr,456size,457min,458max,459gfp.as_raw(),460)461});462463if let Err(err) = res {464// SAFETY: As `mtree_alloc_range` failed, it is safe to take back ownership.465let value = unsafe { T::from_foreign(ptr) };466467let cause = if err == ENOMEM {468AllocErrorKind::AllocError(kernel::alloc::AllocError)469} else if err == EBUSY {470AllocErrorKind::Busy471} else {472AllocErrorKind::InvalidRequest473};474Err(AllocError { value, cause })475} else {476Ok(index)477}478}479}480481/// A helper type used for navigating a [`MapleTree`].482///483/// # Invariants484///485/// For the duration of `'tree`:486///487/// * The `ma_state` references a valid `MapleTree<T>`.488/// * The `ma_state` has read/write access to the tree.489pub struct MaState<'tree, T: ForeignOwnable> {490state: bindings::ma_state,491_phantom: PhantomData<&'tree mut MapleTree<T>>,492}493494impl<'tree, T: ForeignOwnable> MaState<'tree, T> {495/// Initialize a new `MaState` with the given tree.496///497/// # Safety498///499/// The caller must ensure that this `MaState` has read/write access to the maple tree.500#[inline]501unsafe fn new_raw(mt: &'tree MapleTree<T>, first: usize, end: usize) -> Self {502// INVARIANT:503// * Having a reference ensures that the `MapleTree<T>` is valid for `'tree`.504// * The caller ensures that we have read/write access.505Self {506state: bindings::ma_state {507tree: mt.tree.get(),508index: first,509last: end,510node: ptr::null_mut(),511status: bindings::maple_status_ma_start,512min: 0,513max: usize::MAX,514alloc: ptr::null_mut(),515mas_flags: 0,516store_type: bindings::store_type_wr_invalid,517..Default::default()518},519_phantom: PhantomData,520}521}522523#[inline]524fn as_raw(&mut self) -> *mut bindings::ma_state {525&raw mut self.state526}527528#[inline]529fn mas_find_raw(&mut self, max: usize) -> *mut c_void {530// SAFETY: By the type invariants, the `ma_state` is active and we have read/write access531// to the tree.532unsafe { bindings::mas_find(self.as_raw(), max) }533}534535/// Find the next entry in the maple tree.536///537/// # Examples538///539/// Iterate the maple tree.540///541/// ```542/// use kernel::maple_tree::MapleTree;543/// use kernel::sync::Arc;544///545/// let tree = KBox::pin_init(MapleTree::<Arc<i32>>::new(), GFP_KERNEL)?;546///547/// let ten = Arc::new(10, GFP_KERNEL)?;548/// let twenty = Arc::new(20, GFP_KERNEL)?;549/// tree.insert(100, ten, GFP_KERNEL)?;550/// tree.insert(200, twenty, GFP_KERNEL)?;551///552/// let mut ma_lock = tree.lock();553/// let mut iter = ma_lock.ma_state(0, usize::MAX);554///555/// assert_eq!(iter.find(usize::MAX).map(|v| *v), Some(10));556/// assert_eq!(iter.find(usize::MAX).map(|v| *v), Some(20));557/// assert!(iter.find(usize::MAX).is_none());558/// # Ok::<_, Error>(())559/// ```560#[inline]561pub fn find(&mut self, max: usize) -> Option<T::BorrowedMut<'_>> {562let ret = self.mas_find_raw(max);563if ret.is_null() {564return None;565}566567// SAFETY: If the pointer is not null, then it references a valid instance of `T`. It's568// safe to access it mutably as the returned reference borrows this `MaState`, and the569// `MaState` has read/write access to the maple tree.570Some(unsafe { T::borrow_mut(ret) })571}572}573574/// Error type for failure to insert a new value.575pub struct InsertError<T> {576/// The value that could not be inserted.577pub value: T,578/// The reason for the failure to insert.579pub cause: InsertErrorKind,580}581582/// The reason for the failure to insert.583#[derive(PartialEq, Eq, Copy, Clone, Debug)]584pub enum InsertErrorKind {585/// There is already a value in the requested range.586Occupied,587/// Failure to allocate memory.588AllocError(kernel::alloc::AllocError),589/// The insertion request was invalid.590InvalidRequest,591}592593impl From<InsertErrorKind> for Error {594#[inline]595fn from(kind: InsertErrorKind) -> Error {596match kind {597InsertErrorKind::Occupied => EEXIST,598InsertErrorKind::AllocError(kernel::alloc::AllocError) => ENOMEM,599InsertErrorKind::InvalidRequest => EINVAL,600}601}602}603604impl<T> From<InsertError<T>> for Error {605#[inline]606fn from(insert_err: InsertError<T>) -> Error {607Error::from(insert_err.cause)608}609}610611/// Error type for failure to insert a new value.612pub struct AllocError<T> {613/// The value that could not be inserted.614pub value: T,615/// The reason for the failure to insert.616pub cause: AllocErrorKind,617}618619/// The reason for the failure to insert.620#[derive(PartialEq, Eq, Copy, Clone)]621pub enum AllocErrorKind {622/// There is not enough space for the requested allocation.623Busy,624/// Failure to allocate memory.625AllocError(kernel::alloc::AllocError),626/// The insertion request was invalid.627InvalidRequest,628}629630impl From<AllocErrorKind> for Error {631#[inline]632fn from(kind: AllocErrorKind) -> Error {633match kind {634AllocErrorKind::Busy => EBUSY,635AllocErrorKind::AllocError(kernel::alloc::AllocError) => ENOMEM,636AllocErrorKind::InvalidRequest => EINVAL,637}638}639}640641impl<T> From<AllocError<T>> for Error {642#[inline]643fn from(insert_err: AllocError<T>) -> Error {644Error::from(insert_err.cause)645}646}647648649