Skip to main content

singe_cuda/memory/pinned/
mod.rs

1//! Page-locked host memory that each CUDA context pools behind [`std::alloc::Allocator`].
2
3mod pool;
4mod slice;
5
6use std::{
7    alloc::{AllocError, Allocator, Layout},
8    ptr::{self, NonNull},
9    result::Result as StdResult,
10    sync::Arc,
11};
12
13pub(crate) use self::pool::PinnedPool;
14use self::pool::same_class;
15pub use self::{pool::PinnedStats, slice::PinnedVecExt};
16use crate::{
17    context::Context,
18    error::{Error, Result},
19    view::{DeviceRegion, HostRegion, ZeroableDeviceRepr},
20};
21
22/// An allocator for page-locked host memory, drawn from a pool its CUDA context owns.
23///
24/// Get one from [`Context::pinned_host`].
25/// A `Vec` or `Box` that uses it as its allocator lives in pinned memory, which CUDA copies read and write directly instead of staging through pageable memory.
26/// [`PinnedVec`] is such a vector, and it is what this crate's pinned copies accept.
27/// Cloning is cheap, and all clones from one context share its pool, so a buffer may be freed through any of them.
28///
29/// # GPU work
30///
31/// The pool does not know which buffers queued GPU work still uses.
32/// Keep a buffer alive until that work has finished; scoped copies and this crate's submissions do so.
33///
34/// # Allocation failure
35///
36/// A `Vec` that cannot grow aborts the process, as it does with any allocator.
37/// When the size is known up front, allocate with [`PinnedHost::with_capacity`], [`PinnedHost::from_slice`], or [`PinnedHost::zeroed`], which return an error instead.
38///
39/// # How it works
40///
41/// The pool takes chunks of at least 2 MiB from `cudaHostAlloc` and splits them into blocks.
42/// Blocks up to 2 MiB come in power-of-two sizes from 256 bytes, and a larger block gets a chunk of its own, rounded up to a multiple of 2 MiB.
43/// Dropping a buffer returns its block to the pool without a CUDA call, so it is cheap and allowed inside a stream callback.
44/// [`PinnedHost::release_cached`] returns unused chunks to CUDA.
45/// Chunks are portable and mapped, so any context can copy from them.
46#[derive(Debug, Clone)]
47pub struct PinnedHost(Arc<Context>);
48
49/// A vector in page-locked host memory, which CUDA copies read and write without staging.
50pub type PinnedVec<T> = Vec<T, PinnedHost>;
51
52impl Context {
53    /// Returns the allocator for this context's pinned host memory pool.
54    #[must_use]
55    pub fn pinned_host(self: &Arc<Self>) -> PinnedHost {
56        PinnedHost(Arc::clone(self))
57    }
58}
59
60impl PinnedHost {
61    /// Returns the context whose pool this allocator uses.
62    #[must_use]
63    pub fn context(&self) -> &Arc<Context> {
64        &self.0
65    }
66
67    /// Allocates an empty vector with room for exactly `capacity` values.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error if the byte size overflows, `T` needs an alignment above 4096 bytes, the context cannot be bound, or CUDA cannot allocate page-locked memory.
72    pub fn with_capacity<T>(&self, capacity: usize) -> Result<PinnedVec<T>> {
73        let layout = Layout::array::<T>(capacity)
74            .map_err(|_| Error::out_of_range("pinned vector capacity"))?;
75        let block = self.allocate_block(layout)?;
76        // SAFETY: the block holds `capacity` values of `T`, allocated by this allocator with `T`'s array layout.
77        Ok(
78            unsafe {
79                Vec::from_raw_parts_in(block.cast::<T>().as_ptr(), 0, capacity, self.clone())
80            },
81        )
82    }
83
84    /// Allocates a vector holding a copy of `values`.
85    ///
86    /// # Errors
87    ///
88    /// Returns an error if allocation fails, for the reasons [`PinnedHost::with_capacity`] gives.
89    pub fn from_slice<T: Copy>(&self, values: &[T]) -> Result<PinnedVec<T>> {
90        let mut vector = self.with_capacity(values.len())?;
91        vector.extend_from_slice(values);
92        Ok(vector)
93    }
94
95    /// Allocates a vector of `length` zero values.
96    ///
97    /// # Errors
98    ///
99    /// Returns an error if allocation fails, for the reasons [`PinnedHost::with_capacity`] gives.
100    pub fn zeroed<T: ZeroableDeviceRepr>(&self, length: usize) -> Result<PinnedVec<T>> {
101        let mut vector = self.with_capacity::<T>(length)?;
102        // SAFETY: the capacity holds `length` values, and every all-zero `T` is valid.
103        unsafe {
104            ptr::write_bytes(vector.as_mut_ptr(), 0, length);
105            vector.set_len(length);
106        }
107        Ok(vector)
108    }
109
110    /// Frees the pool's chunks whose blocks are all free.
111    ///
112    /// Chunks with a live block stay.
113    /// The pool also frees idle single-block chunks on its own, when an allocation finds no free block of its size.
114    ///
115    /// # Errors
116    ///
117    /// Returns an error if the context cannot be bound or CUDA fails to free a chunk; every idle chunk leaves the pool either way.
118    pub fn release_cached(&self) -> Result<()> {
119        self.0.pinned.release_cached(&self.0)
120    }
121
122    /// Returns how many bytes and chunks the pool holds, and how many bytes are in use.
123    #[must_use]
124    pub fn stats(&self) -> PinnedStats {
125        self.0.pinned.stats()
126    }
127
128    pub(crate) fn host_region(&self, pointer: *const u8, bytes: usize) -> HostRegion<'_> {
129        self.0.pinned.host_region(&self.0, pointer, bytes)
130    }
131
132    pub(crate) fn device_region(
133        &self,
134        pointer: *const u8,
135        bytes: usize,
136    ) -> Result<DeviceRegion<'_>> {
137        self.0.pinned.device_region(&self.0, pointer, bytes)
138    }
139
140    // Requires what `Allocator::grow` or `Allocator::shrink` requires: `block` is live from this allocator with layout `old`.
141    unsafe fn resize(
142        &self,
143        block: NonNull<u8>,
144        old: Layout,
145        new: Layout,
146        zeroed: bool,
147    ) -> StdResult<NonNull<[u8]>, AllocError> {
148        // A block keeps serving a layout of its own class, and `deallocate` with the new layout finds that class.
149        if old.size() != 0 && new.size() != 0 && same_class(old, new) {
150            if zeroed && new.size() > old.size() {
151                // SAFETY: the block's class covers `new.size()` bytes.
152                unsafe {
153                    ptr::write_bytes(block.add(old.size()).as_ptr(), 0, new.size() - old.size());
154                };
155            }
156            return Ok(NonNull::slice_from_raw_parts(block, new.size()));
157        }
158
159        let moved = if zeroed {
160            self.allocate_zeroed(new)?
161        } else {
162            self.allocate(new)?
163        };
164        // SAFETY: both blocks hold at least the smaller size, and distinct live blocks never overlap.
165        unsafe {
166            ptr::copy_nonoverlapping(
167                block.as_ptr(),
168                moved.cast::<u8>().as_ptr(),
169                old.size().min(new.size()),
170            );
171            self.deallocate(block, old);
172        }
173        Ok(moved)
174    }
175
176    fn allocate_block(&self, layout: Layout) -> Result<NonNull<u8>> {
177        if layout.size() == 0 {
178            return NonNull::new(ptr::without_provenance_mut(layout.align()))
179                .ok_or(Error::NullHandle);
180        }
181        self.0.pinned.allocate(&self.0, layout)
182    }
183}
184
185// SAFETY: every clone shares one context and so one pool, which outlives every block because each block's owner holds the context.
186// Blocks are disjoint pieces of page-locked host allocations, and the pool neither reads them nor unwinds.
187/// Allocates blocks from the context's pool.
188/// A zero-sized layout takes no memory.
189/// Growing or shrinking keeps a block in place while the new layout falls in the block's size class.
190unsafe impl Allocator for PinnedHost {
191    fn allocate(&self, layout: Layout) -> StdResult<NonNull<[u8]>, AllocError> {
192        let block = self.allocate_block(layout).map_err(|_| AllocError)?;
193        Ok(NonNull::slice_from_raw_parts(block, layout.size()))
194    }
195
196    unsafe fn deallocate(&self, block: NonNull<u8>, layout: Layout) {
197        if layout.size() != 0 {
198            self.0.pinned.deallocate(block, layout);
199        }
200    }
201
202    unsafe fn grow(
203        &self,
204        block: NonNull<u8>,
205        old: Layout,
206        new: Layout,
207    ) -> StdResult<NonNull<[u8]>, AllocError> {
208        // SAFETY: `grow`'s caller passes a live `block` of this allocator with layout `old`, which is what `resize` requires.
209        unsafe { self.resize(block, old, new, false) }
210    }
211
212    unsafe fn grow_zeroed(
213        &self,
214        block: NonNull<u8>,
215        old: Layout,
216        new: Layout,
217    ) -> StdResult<NonNull<[u8]>, AllocError> {
218        // SAFETY: `grow_zeroed`'s caller passes a live `block` of this allocator with layout `old`, which is what `resize` requires.
219        unsafe { self.resize(block, old, new, true) }
220    }
221
222    unsafe fn shrink(
223        &self,
224        block: NonNull<u8>,
225        old: Layout,
226        new: Layout,
227    ) -> StdResult<NonNull<[u8]>, AllocError> {
228        // SAFETY: `shrink`'s caller passes a live `block` of this allocator with layout `old`, which is what `resize` requires.
229        unsafe { self.resize(block, old, new, false) }
230    }
231}