alloc.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Implementation of the kernel's memory allocation infrastructure.
  3. #[cfg(not(any(test, testlib)))]
  4. pub mod allocator;
  5. pub mod kbox;
  6. pub mod kvec;
  7. pub mod layout;
  8. #[cfg(any(test, testlib))]
  9. pub mod allocator_test;
  10. #[cfg(any(test, testlib))]
  11. pub use self::allocator_test as allocator;
  12. pub use self::kbox::Box;
  13. pub use self::kbox::KBox;
  14. pub use self::kbox::KVBox;
  15. pub use self::kbox::VBox;
  16. pub use self::kvec::IntoIter;
  17. pub use self::kvec::KVVec;
  18. pub use self::kvec::KVec;
  19. pub use self::kvec::VVec;
  20. pub use self::kvec::Vec;
  21. /// Indicates an allocation error.
  22. #[derive(Copy, Clone, PartialEq, Eq, Debug)]
  23. pub struct AllocError;
  24. use core::{alloc::Layout, ptr::NonNull};
  25. /// Flags to be used when allocating memory.
  26. ///
  27. /// They can be combined with the operators `|`, `&`, and `!`.
  28. ///
  29. /// Values can be used from the [`flags`] module.
  30. #[derive(Clone, Copy, PartialEq)]
  31. pub struct Flags(u32);
  32. impl Flags {
  33. /// Get the raw representation of this flag.
  34. pub(crate) fn as_raw(self) -> u32 {
  35. self.0
  36. }
  37. /// Check whether `flags` is contained in `self`.
  38. pub fn contains(self, flags: Flags) -> bool {
  39. (self & flags) == flags
  40. }
  41. }
  42. impl core::ops::BitOr for Flags {
  43. type Output = Self;
  44. fn bitor(self, rhs: Self) -> Self::Output {
  45. Self(self.0 | rhs.0)
  46. }
  47. }
  48. impl core::ops::BitAnd for Flags {
  49. type Output = Self;
  50. fn bitand(self, rhs: Self) -> Self::Output {
  51. Self(self.0 & rhs.0)
  52. }
  53. }
  54. impl core::ops::Not for Flags {
  55. type Output = Self;
  56. fn not(self) -> Self::Output {
  57. Self(!self.0)
  58. }
  59. }
  60. /// Allocation flags.
  61. ///
  62. /// These are meant to be used in functions that can allocate memory.
  63. pub mod flags {
  64. use super::Flags;
  65. /// Zeroes out the allocated memory.
  66. ///
  67. /// This is normally or'd with other flags.
  68. pub const __GFP_ZERO: Flags = Flags(bindings::__GFP_ZERO);
  69. /// Allow the allocation to be in high memory.
  70. ///
  71. /// Allocations in high memory may not be mapped into the kernel's address space, so this can't
  72. /// be used with `kmalloc` and other similar methods.
  73. ///
  74. /// This is normally or'd with other flags.
  75. pub const __GFP_HIGHMEM: Flags = Flags(bindings::__GFP_HIGHMEM);
  76. /// Users can not sleep and need the allocation to succeed.
  77. ///
  78. /// A lower watermark is applied to allow access to "atomic reserves". The current
  79. /// implementation doesn't support NMI and few other strict non-preemptive contexts (e.g.
  80. /// raw_spin_lock). The same applies to [`GFP_NOWAIT`].
  81. pub const GFP_ATOMIC: Flags = Flags(bindings::GFP_ATOMIC);
  82. /// Typical for kernel-internal allocations. The caller requires ZONE_NORMAL or a lower zone
  83. /// for direct access but can direct reclaim.
  84. pub const GFP_KERNEL: Flags = Flags(bindings::GFP_KERNEL);
  85. /// The same as [`GFP_KERNEL`], except the allocation is accounted to kmemcg.
  86. pub const GFP_KERNEL_ACCOUNT: Flags = Flags(bindings::GFP_KERNEL_ACCOUNT);
  87. /// For kernel allocations that should not stall for direct reclaim, start physical IO or
  88. /// use any filesystem callback. It is very likely to fail to allocate memory, even for very
  89. /// small allocations.
  90. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT);
  91. /// Suppresses allocation failure reports.
  92. ///
  93. /// This is normally or'd with other flags.
  94. pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN);
  95. }
  96. /// The kernel's [`Allocator`] trait.
  97. ///
  98. /// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described
  99. /// via [`Layout`].
  100. ///
  101. /// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on
  102. /// an object instance.
  103. ///
  104. /// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design
  105. /// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind
  106. /// of `self` parameter.
  107. ///
  108. /// # Safety
  109. ///
  110. /// - A memory allocation returned from an allocator must remain valid until it is explicitly freed.
  111. ///
  112. /// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`]
  113. /// function of the same type.
  114. ///
  115. /// - Implementers must ensure that all trait functions abide by the guarantees documented in the
  116. /// `# Guarantees` sections.
  117. pub unsafe trait Allocator {
  118. /// Allocate memory based on `layout` and `flags`.
  119. ///
  120. /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout
  121. /// constraints (i.e. minimum size and alignment as specified by `layout`).
  122. ///
  123. /// This function is equivalent to `realloc` when called with `None`.
  124. ///
  125. /// # Guarantees
  126. ///
  127. /// When the return value is `Ok(ptr)`, then `ptr` is
  128. /// - valid for reads and writes for `layout.size()` bytes, until it is passed to
  129. /// [`Allocator::free`] or [`Allocator::realloc`],
  130. /// - aligned to `layout.align()`,
  131. ///
  132. /// Additionally, `Flags` are honored as documented in
  133. /// <https://docs.kernel.org/core-api/mm-api.html#mm-api-gfp-flags>.
  134. fn alloc(layout: Layout, flags: Flags) -> Result<NonNull<[u8]>, AllocError> {
  135. // SAFETY: Passing `None` to `realloc` is valid by its safety requirements and asks for a
  136. // new memory allocation.
  137. unsafe { Self::realloc(None, layout, Layout::new::<()>(), flags) }
  138. }
  139. /// Re-allocate an existing memory allocation to satisfy the requested `layout`.
  140. ///
  141. /// If the requested size is zero, `realloc` behaves equivalent to `free`.
  142. ///
  143. /// If the requested size is larger than the size of the existing allocation, a successful call
  144. /// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but
  145. /// may also be larger.
  146. ///
  147. /// If the requested size is smaller than the size of the existing allocation, `realloc` may or
  148. /// may not shrink the buffer; this is implementation specific to the allocator.
  149. ///
  150. /// On allocation failure, the existing buffer, if any, remains valid.
  151. ///
  152. /// The buffer is represented as `NonNull<[u8]>`.
  153. ///
  154. /// # Safety
  155. ///
  156. /// - If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation
  157. /// created by this [`Allocator`]; if `old_layout` is zero-sized `p` does not need to be a
  158. /// pointer returned by this [`Allocator`].
  159. /// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and
  160. /// `old_layout` is ignored.
  161. /// - `old_layout` must match the `Layout` the allocation has been created with.
  162. ///
  163. /// # Guarantees
  164. ///
  165. /// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then
  166. /// it additionally guarantees that:
  167. /// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new
  168. /// and old size, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] ==
  169. /// p[0..min(layout.size(), old_layout.size())]`.
  170. /// - when the return value is `Err(AllocError)`, then `ptr` is still valid.
  171. unsafe fn realloc(
  172. ptr: Option<NonNull<u8>>,
  173. layout: Layout,
  174. old_layout: Layout,
  175. flags: Flags,
  176. ) -> Result<NonNull<[u8]>, AllocError>;
  177. /// Free an existing memory allocation.
  178. ///
  179. /// # Safety
  180. ///
  181. /// - `ptr` must point to an existing and valid memory allocation created by this [`Allocator`];
  182. /// if `old_layout` is zero-sized `p` does not need to be a pointer returned by this
  183. /// [`Allocator`].
  184. /// - `layout` must match the `Layout` the allocation has been created with.
  185. /// - The memory allocation at `ptr` must never again be read from or written to.
  186. unsafe fn free(ptr: NonNull<u8>, layout: Layout) {
  187. // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this
  188. // allocator. We are passing a `Layout` with the smallest possible alignment, so it is
  189. // smaller than or equal to the alignment previously used with this allocation.
  190. let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) };
  191. }
  192. }
  193. /// Returns a properly aligned dangling pointer from the given `layout`.
  194. pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> {
  195. let ptr = layout.align() as *mut u8;
  196. // SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero.
  197. unsafe { NonNull::new_unchecked(ptr) }
  198. }