Skip to main content

singe_cuda/memory/pinned/
pool.rs

1use std::{
2    alloc::Layout,
3    collections::BTreeMap,
4    fmt::{self, Debug, Formatter},
5    mem,
6    ptr::{self, NonNull},
7    sync::{Arc, Mutex, MutexGuard, PoisonError},
8};
9
10use singe_core::report_cleanup_failure;
11use singe_cuda_sys::runtime;
12
13use crate::{
14    context::Context,
15    error::{Error, Result},
16    memory::{free_host_raw, mapped_host_device_ptr},
17    try_ffi,
18    view::{AllocationId, DeviceRegion, HostRegion},
19};
20
21const SMALLEST_BLOCK: usize = 256;
22
23const LARGEST_ALIGNMENT: usize = 4096;
24
25const CHUNK_BYTES: usize = 2 << 20;
26
27#[derive(Default)]
28pub(crate) struct PinnedPool {
29    state: Mutex<PoolState>,
30}
31
32/// Byte and chunk counts of a context's pinned host memory pool.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub struct PinnedStats {
35    /// Bytes the pool holds from CUDA, in free and live blocks.
36    pub reserved_bytes: usize,
37    /// Bytes in live blocks, each counted at its size class.
38    pub active_bytes: usize,
39    /// Allocations the pool holds from CUDA.
40    pub chunks: usize,
41}
42
43#[derive(Debug, Default)]
44struct PoolState {
45    chunks: BTreeMap<usize, Chunk>,
46    free: BTreeMap<usize, Vec<NonNull<u8>>>,
47    active_bytes: usize,
48}
49
50#[derive(Debug)]
51struct Chunk {
52    base: NonNull<u8>,
53    bytes: usize,
54    class: usize,
55    id: AllocationId,
56    free_blocks: usize,
57}
58
59#[expect(
60    clippy::non_send_fields_in_send_ty,
61    reason = "block pointers are addresses the pool hands out, never dereferenced"
62)]
63// SAFETY: the block pointers are addresses into portable page-locked chunks that any thread may hand out or free, the pool never dereferences them, and the pool's mutex serializes every access to this state.
64unsafe impl Send for PoolState {}
65
66impl Debug for PinnedPool {
67    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
68        // The free lists hold thousands of pointers, which would flood the `Debug` output of every `Context`.
69        formatter
70            .debug_struct("PinnedPool")
71            .field("stats", &self.stats())
72            .finish()
73    }
74}
75
76impl PinnedPool {
77    pub(crate) fn allocate(&self, context: &Context, layout: Layout) -> Result<NonNull<u8>> {
78        let class = class(layout)?;
79        let cached = self.lock().take(class);
80        if let Some(block) = cached {
81            return Ok(block);
82        }
83
84        // CUDA runs outside the lock, since `cudaFreeHost` may wait for a stream callback that drops a pinned buffer.
85        context.bind()?;
86        // A failed free leaves the chunk out of the pool, and this allocation does not depend on it.
87        let dedicated = self.lock().take_idle(Chunk::is_dedicated);
88        if let Err(error) = free_chunks(dedicated) {
89            report_cleanup_failure("free", "cuda pinned host memory", &error);
90        }
91
92        let chunk = if let Ok(chunk) = Chunk::allocate(class) {
93            chunk
94        } else {
95            let idle = self.lock().take_idle(|_| true);
96            if let Err(error) = free_chunks(idle) {
97                report_cleanup_failure("free", "cuda pinned host memory", &error);
98            }
99
100            Chunk::allocate(class)?
101        };
102
103        let mut state = self.lock();
104        state.insert(chunk);
105        state
106            .take(class)
107            .ok_or_else(|| Error::out_of_range("pinned size class"))
108    }
109
110    pub(crate) fn deallocate(&self, block: NonNull<u8>, layout: Layout) {
111        // Never calls CUDA, so dropping a pinned buffer is cheap and works inside a stream callback.
112        if let Ok(class) = class(layout) {
113            self.lock().give_back(block, class);
114        }
115    }
116
117    pub(crate) fn release_cached(&self, context: &Context) -> Result<()> {
118        context.bind()?;
119        let idle = self.lock().take_idle(|_| true);
120        free_chunks(idle)
121    }
122
123    pub(crate) fn release_all(&self, context: &Context) -> Result<()> {
124        let chunks = {
125            let mut state = self.lock();
126            debug_assert_eq!(
127                state.active_bytes, 0,
128                "pinned blocks outlived their context"
129            );
130            state.free.clear();
131            mem::take(&mut state.chunks)
132        };
133        if chunks.is_empty() {
134            return Ok(());
135        }
136
137        context.bind()?;
138        free_chunks(chunks.into_values().collect())
139    }
140
141    pub(crate) fn stats(&self) -> PinnedStats {
142        let state = self.lock();
143        PinnedStats {
144            reserved_bytes: state.chunks.values().map(|chunk| chunk.bytes).sum(),
145            active_bytes: state.active_bytes,
146            chunks: state.chunks.len(),
147        }
148    }
149
150    pub(crate) fn host_region<'a>(
151        &self,
152        context: &'a Arc<Context>,
153        pointer: *const u8,
154        bytes: usize,
155    ) -> HostRegion<'a> {
156        let chunk = self
157            .lock()
158            .chunk_holding(pointer.addr())
159            .map(|chunk| (chunk.id, chunk.bytes, chunk.base.addr().get()));
160        let Some((id, chunk_bytes, base)) = chunk else {
161            // SAFETY: an empty range has no bytes for any alias to share.
162            return unsafe { HostRegion::from_raw_parts(context, AllocationId::create(), 0, true) };
163        };
164
165        let offset = pointer.addr() - base;
166        // SAFETY: the chunk stays allocated while the context lives, and it is portable and mapped.
167        unsafe { HostRegion::from_raw_parts(context, id, chunk_bytes, true) }
168            .slice(offset..offset + bytes)
169            .expect("pinned block lies inside its chunk")
170    }
171
172    pub(crate) fn device_region<'a>(
173        &self,
174        context: &'a Arc<Context>,
175        pointer: *const u8,
176        bytes: usize,
177    ) -> Result<DeviceRegion<'a>> {
178        let chunk = self
179            .lock()
180            .chunk_holding(pointer.addr())
181            .map(|chunk| (chunk.id, chunk.bytes, chunk.base));
182        let Some((id, chunk_bytes, base)) = chunk else {
183            // SAFETY: an empty range has no bytes for any alias to share.
184            return unsafe {
185                DeviceRegion::from_raw_parts(context, AllocationId::create(), ptr::null_mut(), 0)
186            };
187        };
188
189        // Asked per view, so a device that cannot map host memory fails here, not on every allocation.
190        context.bind()?;
191        let device = mapped_host_device_ptr(base.as_ptr().cast())?;
192        let offset = pointer.addr() - base.addr().get();
193        // SAFETY: the chunk stays allocated and mapped while the context lives, and its device alias shares the host region's identity.
194        unsafe { DeviceRegion::from_raw_parts(context, id, device.as_raw().cast(), chunk_bytes)? }
195            .slice(offset..offset + bytes)
196    }
197
198    fn lock(&self) -> MutexGuard<'_, PoolState> {
199        // A panic elsewhere must not make `deallocate` unwind, and the state stays consistent at every unlock.
200        self.state.lock().unwrap_or_else(PoisonError::into_inner)
201    }
202}
203
204impl PoolState {
205    fn take(&mut self, class: usize) -> Option<NonNull<u8>> {
206        let block = self.free.get_mut(&class)?.pop()?;
207        if let Some(chunk) = self.chunk_holding_mut(block.addr().get()) {
208            chunk.free_blocks -= 1;
209        }
210
211        self.active_bytes += class;
212        Some(block)
213    }
214
215    fn give_back(&mut self, block: NonNull<u8>, class: usize) {
216        if let Some(chunk) = self.chunk_holding_mut(block.addr().get()) {
217            chunk.free_blocks += 1;
218        }
219
220        self.active_bytes -= class;
221        self.free.entry(class).or_default().push(block);
222    }
223
224    fn insert(&mut self, chunk: Chunk) {
225        let blocks = self.free.entry(chunk.class).or_default();
226        blocks.extend((0..chunk.free_blocks).map(|index| {
227            // SAFETY: `index` is below `bytes / class`, so each block starts inside the chunk's allocation.
228            unsafe { chunk.base.add(index * chunk.class) }
229        }));
230        self.chunks.insert(chunk.base.addr().get(), chunk);
231    }
232
233    fn take_idle(&mut self, selected: impl Fn(&Chunk) -> bool) -> Vec<Chunk> {
234        let idle = self
235            .chunks
236            .extract_if(.., |_, chunk| chunk.is_idle() && selected(chunk))
237            .map(|(_, chunk)| chunk)
238            .collect::<Vec<_>>();
239        for chunk in &idle {
240            if let Some(blocks) = self.free.get_mut(&chunk.class) {
241                blocks.retain(|block| !chunk.holds(block.addr().get()));
242            }
243        }
244        idle
245    }
246
247    fn chunk_holding(&self, address: usize) -> Option<&Chunk> {
248        let (_, chunk) = self.chunks.range(..=address).next_back()?;
249        chunk.holds(address).then_some(chunk)
250    }
251
252    fn chunk_holding_mut(&mut self, address: usize) -> Option<&mut Chunk> {
253        let (_, chunk) = self.chunks.range_mut(..=address).next_back()?;
254        chunk.holds(address).then_some(chunk)
255    }
256}
257
258impl Chunk {
259    fn allocate(class: usize) -> Result<Self> {
260        let bytes = class.max(CHUNK_BYTES);
261        let mut pointer = ptr::null_mut();
262        // SAFETY: `pointer` is a writable local, and `bytes` is at least `SMALLEST_BLOCK`, since every class is.
263        unsafe {
264            try_ffi!(runtime::cudaHostAlloc(
265                &raw mut pointer,
266                bytes as _,
267                runtime::cudaHostAllocPortable | runtime::cudaHostAllocMapped,
268            ))?;
269        }
270
271        let chunk = Self {
272            base: NonNull::new(pointer.cast::<u8>()).ok_or(Error::NullHandle)?,
273            bytes,
274            class,
275            id: AllocationId::create(),
276            free_blocks: bytes / class,
277        };
278        // Block alignment rests on page-aligned chunks, which CUDA gives in practice but does not document.
279        if !chunk.base.addr().get().is_multiple_of(LARGEST_ALIGNMENT) {
280            chunk.free()?;
281            return Err(Error::UnsupportedPinnedAlignment {
282                align: LARGEST_ALIGNMENT,
283            });
284        }
285        Ok(chunk)
286    }
287
288    const fn is_idle(&self) -> bool {
289        self.free_blocks == self.bytes / self.class
290    }
291
292    const fn is_dedicated(&self) -> bool {
293        // A chunk of one block is released when idle at the next miss, so large buffers do not stay pinned for the context's life.
294        self.class >= CHUNK_BYTES
295    }
296
297    fn holds(&self, address: usize) -> bool {
298        (self.base.addr().get()..self.base.addr().get() + self.bytes).contains(&address)
299    }
300
301    fn free(&self) -> Result<()> {
302        // SAFETY: the chunk came from `cudaHostAlloc`, its pool frees it once, and none of its blocks is live.
303        unsafe { free_host_raw(self.base.as_ptr().cast()) }
304    }
305}
306
307fn free_chunks(chunks: Vec<Chunk>) -> Result<()> {
308    let mut result = Ok(());
309    for chunk in chunks {
310        if let Err(error) = chunk.free() {
311            result = Err(error);
312        }
313    }
314    result
315}
316
317pub(crate) fn same_class(first: Layout, second: Layout) -> bool {
318    matches!((class(first), class(second)), (Ok(first), Ok(second)) if first == second)
319}
320
321fn class(layout: Layout) -> Result<usize> {
322    // A layout always maps to the same class, since `deallocate` receives the layout `allocate` did.
323    // Small classes are powers of two, so a block is aligned to its class up to a page; large ones round to whole chunks, wasting less than a power of two would.
324    if layout.align() > LARGEST_ALIGNMENT {
325        return Err(Error::UnsupportedPinnedAlignment {
326            align: layout.align(),
327        });
328    }
329
330    let bytes = layout.size().max(layout.align()).max(SMALLEST_BLOCK);
331    if bytes > CHUNK_BYTES {
332        bytes.checked_next_multiple_of(CHUNK_BYTES)
333    } else {
334        bytes.checked_next_power_of_two()
335    }
336    .ok_or_else(|| Error::out_of_range("pinned block size"))
337}