1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Maple trees. 4 //! 5 //! C header: [`include/linux/maple_tree.h`](srctree/include/linux/maple_tree.h) 6 //! 7 //! Reference: <https://docs.kernel.org/core-api/maple_tree.html> 8 9 use core::{ 10 marker::PhantomData, 11 ops::{Bound, RangeBounds}, 12 ptr, 13 }; 14 15 use kernel::{ 16 alloc::Flags, 17 error::to_result, 18 prelude::*, 19 types::{ 20 ForeignOwnable, 21 NotThreadSafe, 22 Opaque, // 23 }, 24 }; 25 26 /// A maple tree optimized for storing non-overlapping ranges. 27 /// 28 /// # Invariants 29 /// 30 /// Each range in the maple tree owns an instance of `T`. 31 #[pin_data(PinnedDrop)] 32 #[repr(transparent)] 33 pub struct MapleTree<T: ForeignOwnable> { 34 #[pin] 35 tree: Opaque<bindings::maple_tree>, 36 _p: PhantomData<T>, 37 } 38 39 /// A maple tree with `MT_FLAGS_ALLOC_RANGE` set. 40 /// 41 /// All methods on [`MapleTree`] are also accessible on this type. 42 #[pin_data] 43 #[repr(transparent)] 44 pub struct MapleTreeAlloc<T: ForeignOwnable> { 45 #[pin] 46 tree: MapleTree<T>, 47 } 48 49 // Make MapleTree methods usable on MapleTreeAlloc. 50 impl<T: ForeignOwnable> core::ops::Deref for MapleTreeAlloc<T> { 51 type Target = MapleTree<T>; 52 53 #[inline] 54 fn deref(&self) -> &MapleTree<T> { 55 &self.tree 56 } 57 } 58 59 #[inline] 60 fn to_maple_range(range: impl RangeBounds<usize>) -> Option<(usize, usize)> { 61 let first = match range.start_bound() { 62 Bound::Included(start) => *start, 63 Bound::Excluded(start) => start.checked_add(1)?, 64 Bound::Unbounded => 0, 65 }; 66 67 let last = match range.end_bound() { 68 Bound::Included(end) => *end, 69 Bound::Excluded(end) => end.checked_sub(1)?, 70 Bound::Unbounded => usize::MAX, 71 }; 72 73 if last < first { 74 return None; 75 } 76 77 Some((first, last)) 78 } 79 80 impl<T: ForeignOwnable> MapleTree<T> { 81 /// Create a new maple tree. 82 /// 83 /// The tree will use the regular implementation with a higher branching factor, rather than 84 /// the allocation tree. 85 #[inline] 86 pub fn new() -> impl PinInit<Self> { 87 pin_init!(MapleTree { 88 // SAFETY: This initializes a maple tree into a pinned slot. The maple tree will be 89 // destroyed in Drop before the memory location becomes invalid. 90 tree <- Opaque::ffi_init(|slot| unsafe { bindings::mt_init_flags(slot, 0) }), 91 _p: PhantomData, 92 }) 93 } 94 95 /// Insert the value at the given index. 96 /// 97 /// # Errors 98 /// 99 /// If the maple tree already contains a range using the given index, then this call will 100 /// return an [`InsertErrorKind::Occupied`]. It may also fail if memory allocation fails. 101 /// 102 /// # Examples 103 /// 104 /// ``` 105 /// use kernel::maple_tree::{InsertErrorKind, MapleTree}; 106 /// 107 /// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?; 108 /// 109 /// let ten = KBox::new(10, GFP_KERNEL)?; 110 /// let twenty = KBox::new(20, GFP_KERNEL)?; 111 /// let the_answer = KBox::new(42, GFP_KERNEL)?; 112 /// 113 /// // These calls will succeed. 114 /// tree.insert(100, ten, GFP_KERNEL)?; 115 /// tree.insert(101, twenty, GFP_KERNEL)?; 116 /// 117 /// // This will fail because the index is already in use. 118 /// assert_eq!( 119 /// tree.insert(100, the_answer, GFP_KERNEL).unwrap_err().cause, 120 /// InsertErrorKind::Occupied, 121 /// ); 122 /// # Ok::<_, Error>(()) 123 /// ``` 124 #[inline] 125 pub fn insert(&self, index: usize, value: T, gfp: Flags) -> Result<(), InsertError<T>> { 126 self.insert_range(index..=index, value, gfp) 127 } 128 129 /// Insert a value to the specified range, failing on overlap. 130 /// 131 /// This accepts the usual types of Rust ranges using the `..` and `..=` syntax for exclusive 132 /// and inclusive ranges respectively. The range must not be empty, and must not overlap with 133 /// any existing range. 134 /// 135 /// # Errors 136 /// 137 /// If the maple tree already contains an overlapping range, then this call will return an 138 /// [`InsertErrorKind::Occupied`]. It may also fail if memory allocation fails or if the 139 /// requested range is invalid (e.g. empty). 140 /// 141 /// # Examples 142 /// 143 /// ``` 144 /// use kernel::maple_tree::{InsertErrorKind, MapleTree}; 145 /// 146 /// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?; 147 /// 148 /// let ten = KBox::new(10, GFP_KERNEL)?; 149 /// let twenty = KBox::new(20, GFP_KERNEL)?; 150 /// let the_answer = KBox::new(42, GFP_KERNEL)?; 151 /// let hundred = KBox::new(100, GFP_KERNEL)?; 152 /// 153 /// // Insert the value 10 at the indices 100 to 499. 154 /// tree.insert_range(100..500, ten, GFP_KERNEL)?; 155 /// 156 /// // Insert the value 20 at the indices 500 to 1000. 157 /// tree.insert_range(500..=1000, twenty, GFP_KERNEL)?; 158 /// 159 /// // This will fail due to overlap with the previous range on index 1000. 160 /// assert_eq!( 161 /// tree.insert_range(1000..1200, the_answer, GFP_KERNEL).unwrap_err().cause, 162 /// InsertErrorKind::Occupied, 163 /// ); 164 /// 165 /// // When using .. to specify the range, you must be careful to ensure that the range is 166 /// // non-empty. 167 /// assert_eq!( 168 /// tree.insert_range(72..72, hundred, GFP_KERNEL).unwrap_err().cause, 169 /// InsertErrorKind::InvalidRequest, 170 /// ); 171 /// # Ok::<_, Error>(()) 172 /// ``` 173 pub fn insert_range<R>(&self, range: R, value: T, gfp: Flags) -> Result<(), InsertError<T>> 174 where 175 R: RangeBounds<usize>, 176 { 177 let Some((first, last)) = to_maple_range(range) else { 178 return Err(InsertError { 179 value, 180 cause: InsertErrorKind::InvalidRequest, 181 }); 182 }; 183 184 let ptr = T::into_foreign(value); 185 186 // SAFETY: The tree is valid, and we are passing a pointer to an owned instance of `T`. 187 let res = to_result(unsafe { 188 bindings::mtree_insert_range(self.tree.get(), first, last, ptr, gfp.as_raw()) 189 }); 190 191 if let Err(err) = res { 192 // SAFETY: As `mtree_insert_range` failed, it is safe to take back ownership. 193 let value = unsafe { T::from_foreign(ptr) }; 194 195 let cause = if err == ENOMEM { 196 InsertErrorKind::AllocError(kernel::alloc::AllocError) 197 } else if err == EEXIST { 198 InsertErrorKind::Occupied 199 } else { 200 InsertErrorKind::InvalidRequest 201 }; 202 Err(InsertError { value, cause }) 203 } else { 204 Ok(()) 205 } 206 } 207 208 /// Erase the range containing the given index. 209 /// 210 /// # Examples 211 /// 212 /// ``` 213 /// use kernel::maple_tree::MapleTree; 214 /// 215 /// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?; 216 /// 217 /// let ten = KBox::new(10, GFP_KERNEL)?; 218 /// let twenty = KBox::new(20, GFP_KERNEL)?; 219 /// 220 /// tree.insert_range(100..500, ten, GFP_KERNEL)?; 221 /// tree.insert(67, twenty, GFP_KERNEL)?; 222 /// 223 /// assert_eq!(tree.erase(67).map(|v| *v), Some(20)); 224 /// assert_eq!(tree.erase(275).map(|v| *v), Some(10)); 225 /// 226 /// // The previous call erased the entire range, not just index 275. 227 /// assert!(tree.erase(127).is_none()); 228 /// # Ok::<_, Error>(()) 229 /// ``` 230 #[inline] 231 pub fn erase(&self, index: usize) -> Option<T> { 232 // SAFETY: `self.tree` contains a valid maple tree. 233 let ret = unsafe { bindings::mtree_erase(self.tree.get(), index) }; 234 235 // SAFETY: If the pointer is not null, then we took ownership of a valid instance of `T` 236 // from the tree. 237 unsafe { T::try_from_foreign(ret) } 238 } 239 240 /// Lock the internal spinlock. 241 #[inline] 242 pub fn lock(&self) -> MapleGuard<'_, T> { 243 // SAFETY: It's safe to lock the spinlock in a maple tree. 244 unsafe { bindings::spin_lock(self.ma_lock()) }; 245 246 // INVARIANT: We just took the spinlock. 247 MapleGuard { 248 tree: self, 249 _not_send: NotThreadSafe, 250 } 251 } 252 253 #[inline] 254 fn ma_lock(&self) -> *mut bindings::spinlock_t { 255 // SAFETY: This pointer offset operation stays in-bounds. 256 let lock_ptr = unsafe { &raw mut (*self.tree.get()).__bindgen_anon_1.ma_lock }; 257 lock_ptr.cast() 258 } 259 260 /// Free all `T` instances in this tree. 261 /// 262 /// # Safety 263 /// 264 /// This frees Rust data referenced by the maple tree without removing it from the maple tree, 265 /// leaving it in an invalid state. The caller must ensure that this invalid state cannot be 266 /// observed by the end-user. 267 unsafe fn free_all_entries(self: Pin<&mut Self>) { 268 // SAFETY: The caller provides exclusive access to the entire maple tree, so we have 269 // exclusive access to the entire maple tree despite not holding the lock. 270 let mut ma_state = unsafe { MaState::new_raw(self.into_ref().get_ref(), 0, usize::MAX) }; 271 272 loop { 273 // This uses the raw accessor because we're destroying pointers without removing them 274 // from the maple tree, which is only valid because this is the destructor. 275 // 276 // Take the rcu lock because mas_find_raw() requires that you hold either the spinlock 277 // or the rcu read lock. This is only really required if memory reclaim might 278 // reallocate entries in the tree, as we otherwise have exclusive access. That feature 279 // doesn't exist yet, so for now, taking the rcu lock only serves the purpose of 280 // silencing lockdep. 281 let ptr = { 282 let _rcu = kernel::sync::rcu::Guard::new(); 283 ma_state.mas_find_raw(usize::MAX) 284 }; 285 if ptr.is_null() { 286 break; 287 } 288 // SAFETY: By the type invariants, this pointer references a valid value of type `T`. 289 // By the safety requirements, it is okay to free it without removing it from the maple 290 // tree. 291 drop(unsafe { T::from_foreign(ptr) }); 292 } 293 } 294 } 295 296 #[pinned_drop] 297 impl<T: ForeignOwnable> PinnedDrop for MapleTree<T> { 298 #[inline] 299 fn drop(mut self: Pin<&mut Self>) { 300 // We only iterate the tree if the Rust value has a destructor. 301 if core::mem::needs_drop::<T>() { 302 // SAFETY: Other than the below `mtree_destroy` call, the tree will not be accessed 303 // after this call. 304 unsafe { self.as_mut().free_all_entries() }; 305 } 306 307 // SAFETY: The tree is valid, and will not be accessed after this call. 308 unsafe { bindings::mtree_destroy(self.tree.get()) }; 309 } 310 } 311 312 // SAFETY: `MapleTree<T>` is `Send` if `T` is `Send` because `MapleTree` owns its elements. 313 unsafe impl<T: ForeignOwnable + Send> Send for MapleTree<T> {} 314 315 // SAFETY: `&MapleTree<T>` allows inserting and erasing entries from any thread, so `T: Send` is 316 // required, and shared borrows of entries require `T: Sync`. 317 unsafe impl<T: ForeignOwnable + Send + Sync> Sync for MapleTree<T> {} 318 319 /// A reference to a [`MapleTree`] that owns the inner lock. 320 /// 321 /// # Invariants 322 /// 323 /// This guard owns the inner spinlock. 324 #[must_use = "if unused, the lock will be immediately unlocked"] 325 pub struct MapleGuard<'tree, T: ForeignOwnable> { 326 tree: &'tree MapleTree<T>, 327 // A held spinlock must be released on the same CPU that acquired it. 328 _not_send: NotThreadSafe, 329 } 330 331 impl<'tree, T: ForeignOwnable> Drop for MapleGuard<'tree, T> { 332 #[inline] 333 fn drop(&mut self) { 334 // SAFETY: By the type invariants, we hold this spinlock. 335 unsafe { bindings::spin_unlock(self.tree.ma_lock()) }; 336 } 337 } 338 339 impl<'tree, T: ForeignOwnable> MapleGuard<'tree, T> { 340 /// Create a [`MaState`] protected by this lock guard. 341 pub fn ma_state(&mut self, first: usize, end: usize) -> MaState<'_, T> { 342 // SAFETY: The `MaState` borrows this `MapleGuard`, so it can also borrow the `MapleGuard`s 343 // read/write permissions to the maple tree. 344 unsafe { MaState::new_raw(self.tree, first, end) } 345 } 346 347 /// Load the value at the given index. 348 /// 349 /// # Examples 350 /// 351 /// Read the value while holding the spinlock. 352 /// 353 /// ``` 354 /// use kernel::maple_tree::MapleTree; 355 /// 356 /// let tree = KBox::pin_init(MapleTree::<KBox<i32>>::new(), GFP_KERNEL)?; 357 /// 358 /// let ten = KBox::new(10, GFP_KERNEL)?; 359 /// let twenty = KBox::new(20, GFP_KERNEL)?; 360 /// tree.insert(100, ten, GFP_KERNEL)?; 361 /// tree.insert(200, twenty, GFP_KERNEL)?; 362 /// 363 /// let mut lock = tree.lock(); 364 /// assert_eq!(lock.load(100).map(|v| *v), Some(10)); 365 /// assert_eq!(lock.load(200).map(|v| *v), Some(20)); 366 /// assert_eq!(lock.load(300).map(|v| *v), None); 367 /// # Ok::<_, Error>(()) 368 /// ``` 369 /// 370 /// Increment refcount under the lock, to keep value alive afterwards. 371 /// 372 /// ``` 373 /// use kernel::maple_tree::MapleTree; 374 /// use kernel::sync::Arc; 375 /// 376 /// let tree = KBox::pin_init(MapleTree::<Arc<i32>>::new(), GFP_KERNEL)?; 377 /// 378 /// let ten = Arc::new(10, GFP_KERNEL)?; 379 /// let twenty = Arc::new(20, GFP_KERNEL)?; 380 /// tree.insert(100, ten, GFP_KERNEL)?; 381 /// tree.insert(200, twenty, GFP_KERNEL)?; 382 /// 383 /// // Briefly take the lock to increment the refcount. 384 /// let value = tree.lock().load(100).map(Arc::from); 385 /// 386 /// // At this point, another thread might remove the value. 387 /// tree.erase(100); 388 /// 389 /// // But we can still access it because we took a refcount. 390 /// assert_eq!(value.map(|v| *v), Some(10)); 391 /// # Ok::<_, Error>(()) 392 /// ``` 393 #[inline] 394 pub fn load(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> { 395 // SAFETY: `self.tree` contains a valid maple tree. 396 let ret = unsafe { bindings::mtree_load(self.tree.tree.get(), index) }; 397 if ret.is_null() { 398 return None; 399 } 400 401 // SAFETY: If the pointer is not null, then it references a valid instance of `T`. It is 402 // safe to borrow the instance mutably because the signature of this function enforces that 403 // the mutable borrow is not used after the spinlock is dropped. 404 Some(unsafe { T::borrow_mut(ret) }) 405 } 406 } 407 408 impl<T: ForeignOwnable> MapleTreeAlloc<T> { 409 /// Create a new allocation tree. 410 pub fn new() -> impl PinInit<Self> { 411 let tree = pin_init!(MapleTree { 412 // SAFETY: This initializes a maple tree into a pinned slot. The maple tree will be 413 // destroyed in Drop before the memory location becomes invalid. 414 tree <- Opaque::ffi_init(|slot| unsafe { 415 bindings::mt_init_flags(slot, bindings::MT_FLAGS_ALLOC_RANGE) 416 }), 417 _p: PhantomData, 418 }); 419 420 pin_init!(MapleTreeAlloc { tree <- tree }) 421 } 422 423 /// Insert an entry with the given size somewhere in the given range. 424 /// 425 /// The maple tree will search for a location in the given range where there is space to insert 426 /// the new range. If there is not enough available space, then an error will be returned. 427 /// 428 /// The index of the new range is returned. 429 /// 430 /// # Examples 431 /// 432 /// ``` 433 /// use kernel::maple_tree::{MapleTreeAlloc, AllocErrorKind}; 434 /// 435 /// let tree = KBox::pin_init(MapleTreeAlloc::<KBox<i32>>::new(), GFP_KERNEL)?; 436 /// 437 /// let ten = KBox::new(10, GFP_KERNEL)?; 438 /// let twenty = KBox::new(20, GFP_KERNEL)?; 439 /// let thirty = KBox::new(30, GFP_KERNEL)?; 440 /// let hundred = KBox::new(100, GFP_KERNEL)?; 441 /// 442 /// // Allocate three ranges. 443 /// let idx1 = tree.alloc_range(100, ten, ..1000, GFP_KERNEL)?; 444 /// let idx2 = tree.alloc_range(100, twenty, ..1000, GFP_KERNEL)?; 445 /// let idx3 = tree.alloc_range(100, thirty, ..1000, GFP_KERNEL)?; 446 /// 447 /// assert_eq!(idx1, 0); 448 /// assert_eq!(idx2, 100); 449 /// assert_eq!(idx3, 200); 450 /// 451 /// // This will fail because the remaining space is too small. 452 /// assert_eq!( 453 /// tree.alloc_range(800, hundred, ..1000, GFP_KERNEL).unwrap_err().cause, 454 /// AllocErrorKind::Busy, 455 /// ); 456 /// # Ok::<_, Error>(()) 457 /// ``` 458 pub fn alloc_range<R>( 459 &self, 460 size: usize, 461 value: T, 462 range: R, 463 gfp: Flags, 464 ) -> Result<usize, AllocError<T>> 465 where 466 R: RangeBounds<usize>, 467 { 468 let Some((min, max)) = to_maple_range(range) else { 469 return Err(AllocError { 470 value, 471 cause: AllocErrorKind::InvalidRequest, 472 }); 473 }; 474 475 let ptr = T::into_foreign(value); 476 let mut index = 0; 477 478 // SAFETY: The tree is valid, and we are passing a pointer to an owned instance of `T`. 479 let res = to_result(unsafe { 480 bindings::mtree_alloc_range( 481 self.tree.tree.get(), 482 &mut index, 483 ptr, 484 size, 485 min, 486 max, 487 gfp.as_raw(), 488 ) 489 }); 490 491 if let Err(err) = res { 492 // SAFETY: As `mtree_alloc_range` failed, it is safe to take back ownership. 493 let value = unsafe { T::from_foreign(ptr) }; 494 495 let cause = if err == ENOMEM { 496 AllocErrorKind::AllocError(kernel::alloc::AllocError) 497 } else if err == EBUSY { 498 AllocErrorKind::Busy 499 } else { 500 AllocErrorKind::InvalidRequest 501 }; 502 Err(AllocError { value, cause }) 503 } else { 504 Ok(index) 505 } 506 } 507 } 508 509 /// A helper type used for navigating a [`MapleTree`]. 510 /// 511 /// # Invariants 512 /// 513 /// For the duration of `'tree`: 514 /// 515 /// * The `ma_state` references a valid `MapleTree<T>`. 516 /// * The `ma_state` has read/write access to the tree. 517 pub struct MaState<'tree, T: ForeignOwnable> { 518 state: bindings::ma_state, 519 _phantom: PhantomData<&'tree mut MapleTree<T>>, 520 } 521 522 impl<'tree, T: ForeignOwnable> MaState<'tree, T> { 523 /// Initialize a new `MaState` with the given tree. 524 /// 525 /// # Safety 526 /// 527 /// The caller must ensure that this `MaState` has read/write access to the maple tree. 528 #[inline] 529 unsafe fn new_raw(mt: &'tree MapleTree<T>, first: usize, end: usize) -> Self { 530 // INVARIANT: 531 // * Having a reference ensures that the `MapleTree<T>` is valid for `'tree`. 532 // * The caller ensures that we have read/write access. 533 Self { 534 state: bindings::ma_state { 535 tree: mt.tree.get(), 536 index: first, 537 last: end, 538 node: ptr::null_mut(), 539 status: bindings::maple_status_ma_start, 540 min: 0, 541 max: usize::MAX, 542 alloc: ptr::null_mut(), 543 mas_flags: 0, 544 store_type: bindings::store_type_wr_invalid, 545 ..Default::default() 546 }, 547 _phantom: PhantomData, 548 } 549 } 550 551 #[inline] 552 fn as_raw(&mut self) -> *mut bindings::ma_state { 553 &raw mut self.state 554 } 555 556 #[inline] 557 fn mas_find_raw(&mut self, max: usize) -> *mut c_void { 558 // SAFETY: By the type invariants, the `ma_state` is active and we have read/write access 559 // to the tree. 560 unsafe { bindings::mas_find(self.as_raw(), max) } 561 } 562 563 /// Find the next entry in the maple tree. 564 /// 565 /// # Examples 566 /// 567 /// Iterate the maple tree. 568 /// 569 /// ``` 570 /// use kernel::maple_tree::MapleTree; 571 /// use kernel::sync::Arc; 572 /// 573 /// let tree = KBox::pin_init(MapleTree::<Arc<i32>>::new(), GFP_KERNEL)?; 574 /// 575 /// let ten = Arc::new(10, GFP_KERNEL)?; 576 /// let twenty = Arc::new(20, GFP_KERNEL)?; 577 /// tree.insert(100, ten, GFP_KERNEL)?; 578 /// tree.insert(200, twenty, GFP_KERNEL)?; 579 /// 580 /// let mut ma_lock = tree.lock(); 581 /// let mut iter = ma_lock.ma_state(0, usize::MAX); 582 /// 583 /// assert_eq!(iter.find(usize::MAX).map(|v| *v), Some(10)); 584 /// assert_eq!(iter.find(usize::MAX).map(|v| *v), Some(20)); 585 /// assert!(iter.find(usize::MAX).is_none()); 586 /// # Ok::<_, Error>(()) 587 /// ``` 588 #[inline] 589 pub fn find(&mut self, max: usize) -> Option<T::BorrowedMut<'_>> { 590 let ret = self.mas_find_raw(max); 591 if ret.is_null() { 592 return None; 593 } 594 595 // SAFETY: If the pointer is not null, then it references a valid instance of `T`. It's 596 // safe to access it mutably as the returned reference borrows this `MaState`, and the 597 // `MaState` has read/write access to the maple tree. 598 Some(unsafe { T::borrow_mut(ret) }) 599 } 600 } 601 602 /// Error type for failure to insert a new value. 603 pub struct InsertError<T> { 604 /// The value that could not be inserted. 605 pub value: T, 606 /// The reason for the failure to insert. 607 pub cause: InsertErrorKind, 608 } 609 610 /// The reason for the failure to insert. 611 #[derive(PartialEq, Eq, Copy, Clone, Debug)] 612 pub enum InsertErrorKind { 613 /// There is already a value in the requested range. 614 Occupied, 615 /// Failure to allocate memory. 616 AllocError(kernel::alloc::AllocError), 617 /// The insertion request was invalid. 618 InvalidRequest, 619 } 620 621 impl From<InsertErrorKind> for Error { 622 #[inline] 623 fn from(kind: InsertErrorKind) -> Error { 624 match kind { 625 InsertErrorKind::Occupied => EEXIST, 626 InsertErrorKind::AllocError(kernel::alloc::AllocError) => ENOMEM, 627 InsertErrorKind::InvalidRequest => EINVAL, 628 } 629 } 630 } 631 632 impl<T> From<InsertError<T>> for Error { 633 #[inline] 634 fn from(insert_err: InsertError<T>) -> Error { 635 Error::from(insert_err.cause) 636 } 637 } 638 639 /// Error type for failure to insert a new value. 640 pub struct AllocError<T> { 641 /// The value that could not be inserted. 642 pub value: T, 643 /// The reason for the failure to insert. 644 pub cause: AllocErrorKind, 645 } 646 647 /// The reason for the failure to insert. 648 #[derive(PartialEq, Eq, Copy, Clone)] 649 pub enum AllocErrorKind { 650 /// There is not enough space for the requested allocation. 651 Busy, 652 /// Failure to allocate memory. 653 AllocError(kernel::alloc::AllocError), 654 /// The insertion request was invalid. 655 InvalidRequest, 656 } 657 658 impl From<AllocErrorKind> for Error { 659 #[inline] 660 fn from(kind: AllocErrorKind) -> Error { 661 match kind { 662 AllocErrorKind::Busy => EBUSY, 663 AllocErrorKind::AllocError(kernel::alloc::AllocError) => ENOMEM, 664 AllocErrorKind::InvalidRequest => EINVAL, 665 } 666 } 667 } 668 669 impl<T> From<AllocError<T>> for Error { 670 #[inline] 671 fn from(insert_err: AllocError<T>) -> Error { 672 Error::from(insert_err.cause) 673 } 674 } 675