Skip to main content

singe_cuda/memory/
mod.rs

1//! Device, managed, pinned host, and CUDA array memory.
2
3pub mod array;
4pub mod pattern;
5pub mod peer;
6
7mod allocation;
8mod device;
9mod managed;
10mod pinned;
11mod pitched;
12mod pool;
13mod registered;
14mod stream_ordered;
15pub mod transfer;
16
17use std::{
18    fmt::{self, Display, Formatter},
19    ptr::NonNull,
20};
21
22use bitflags::parser;
23use num_enum::{IntoPrimitive, TryFromPrimitive};
24use singe_core::impl_enum_display;
25use singe_cuda_sys::{
26    driver::{self, CUmemLocationType as MemoryLocationKind},
27    runtime,
28};
29
30pub use self::{
31    allocation::DeviceAllocation,
32    device::{DeviceMemory, RawDeviceMemory},
33    managed::{ManagedMemory, RawManagedMemory},
34    pinned::{PinnedHost, PinnedStats, PinnedVec, PinnedVecExt},
35    pitched::{
36        PitchedDeviceMemory, PitchedDeviceVolume, RawPitchedDeviceMemory, RawPitchedDeviceVolume,
37    },
38    pool::{
39        MemoryAccessDescriptor, MemoryAccessFlag, MemoryAllocationType, MemoryPool,
40        MemoryPoolAttribute, MemoryPoolAttributeValue, MemoryPoolProps, MemoryPoolUsage,
41        RawMemoryPool,
42    },
43    registered::{RegisteredHostMemory, RegisteredHostSlice},
44    stream_ordered::StreamOrderedFree,
45};
46pub(crate) use self::{
47    allocation::{DeferredFree, DeviceDeallocation},
48    pinned::PinnedPool,
49    registered::mapped_host_device_ptr,
50};
51use crate::{
52    driver::entry_points::cuMemGetLocationInfo,
53    error::{Error, Result},
54    try_ffi,
55    types::DevicePtr,
56    utility::to_u64,
57    view::{DeviceRepr, HostRegion, HostSlice, HostSliceMut},
58};
59
60singe_core::native_enum! {
61    /// Direction of a CUDA memory copy.
62    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
63    #[repr(u32)]
64    #[non_exhaustive]
65    pub enum MemoryCopyKind: runtime::cudaMemcpyKind {
66        /// Copies from host memory to host memory.
67        HostToHost = cudaMemcpyHostToHost,
68        /// Copies from host memory to device memory.
69        HostToDevice = cudaMemcpyHostToDevice,
70        /// Copies from device memory to host memory.
71        DeviceToHost = cudaMemcpyDeviceToHost,
72        /// Copies from device memory to device memory.
73        DeviceToDevice = cudaMemcpyDeviceToDevice,
74        /// Direction of the transfer is inferred from the pointer values.
75        /// Requires unified virtual addressing.
76        Default = cudaMemcpyDefault,
77    }
78}
79
80impl_enum_display!(MemoryCopyKind, {
81    Self::HostToHost => "cudaMemcpyHostToHost",
82    Self::HostToDevice => "cudaMemcpyHostToDevice",
83    Self::DeviceToHost => "cudaMemcpyDeviceToHost",
84    Self::DeviceToDevice => "cudaMemcpyDeviceToDevice",
85    Self::Default => "cudaMemcpyDefault",
86});
87
88/// A borrowed CUDA array handle without an allocation owner or lifetime bound.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90#[repr(transparent)]
91pub struct ArrayHandle(runtime::cudaArray_t);
92
93impl ArrayHandle {
94    /// Wraps a native CUDA array handle without taking ownership.
95    ///
96    /// # Safety
97    ///
98    /// `handle` must identify a live CUDA array.
99    /// Keep its native owner alive for every use of this handle or a copy of it, including queued work and graph replays.
100    pub const unsafe fn from_raw(handle: runtime::cudaArray_t) -> Self {
101        Self(handle)
102    }
103
104    /// Returns the borrowed native array handle without retaining its owner.
105    #[must_use]
106    pub const fn as_raw(self) -> runtime::cudaArray_t {
107        self.0
108    }
109}
110
111bitflags::bitflags! {
112    /// Stream visibility of a managed allocation.
113    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114    pub struct MemoryAttachFlags: u32 {
115        /// Memory can be accessed by any stream on any device.
116        const GLOBAL = driver::CUmemAttach_flags::CU_MEM_ATTACH_GLOBAL.0;
117        /// Memory cannot be accessed by any stream on any device.
118        const HOST = driver::CUmemAttach_flags::CU_MEM_ATTACH_HOST.0;
119        /// Memory can only be accessed by a single stream on the associated device.
120        const SINGLE = driver::CUmemAttach_flags::CU_MEM_ATTACH_SINGLE.0;
121    }
122}
123
124impl Display for MemoryAttachFlags {
125    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
126        parser::to_writer(self, f)
127    }
128}
129
130bitflags::bitflags! {
131    /// Flags for CUDA host memory registration.
132    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
133    pub struct HostRegisterFlags: u32 {
134        /// Uses the default host registration policy.
135        const DEFAULT = runtime::cudaHostRegisterDefault;
136        /// Makes the registration recognized as page-locked by other CUDA contexts.
137        const PORTABLE = runtime::cudaHostRegisterPortable;
138        /// Maps the registered range into the CUDA address space for device access.
139        const MAPPED = runtime::cudaHostRegisterMapped;
140        /// Registers memory-mapped I/O storage as non-cache-coherent device memory.
141        const IO_MEMORY = runtime::cudaHostRegisterIoMemory;
142        /// Marks the registered range read-only to CUDA devices.
143        const READ_ONLY = runtime::cudaHostRegisterReadOnly;
144    }
145}
146
147impl Display for HostRegisterFlags {
148    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
149        parser::to_writer(self, f)
150    }
151}
152
153singe_core::native_enum! {
154    /// Kind of memory a pointer addresses.
155    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
156    #[repr(u32)]
157    #[non_exhaustive]
158    pub enum MemoryType: runtime::cudaMemoryType {
159        /// Unregistered memory.
160        Unregistered = cudaMemoryTypeUnregistered,
161        /// Host memory.
162        Host = cudaMemoryTypeHost,
163        /// Device memory.
164        Device = cudaMemoryTypeDevice,
165        /// Managed memory.
166        Managed = cudaMemoryTypeManaged,
167    }
168}
169
170impl_enum_display!(MemoryType, {
171    Self::Unregistered => "cudaMemoryTypeUnregistered",
172    Self::Host => "cudaMemoryTypeHost",
173    Self::Device => "cudaMemoryTypeDevice",
174    Self::Managed => "cudaMemoryTypeManaged",
175});
176
177/// CUDA-reported memory kind, owning device, and accessible aliases for a pointer.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179pub struct PointerAttributes {
180    /// CUDA classification of the memory addressed by the queried pointer.
181    pub memory_type: MemoryType,
182    /// Device ordinal associated with the allocation or registration.
183    pub device: i32,
184    /// Alias usable for device access in the current context, or null when unavailable.
185    pub device_pointer: DevicePtr,
186    /// Alias usable for host access, or null when the memory is not host-accessible.
187    pub host_pointer: *mut (),
188    /// Locality domain ordinal of the allocation; negative when not localized.
189    pub locality_domain_ordinal: i32,
190}
191
192impl TryFrom<runtime::cudaPointerAttributes> for PointerAttributes {
193    type Error = Error;
194
195    fn try_from(attr: runtime::cudaPointerAttributes) -> Result<Self> {
196        Ok(Self {
197            // SAFETY: every field of this union is a plain integer, so reading it is valid for any memory type.
198            locality_domain_ordinal: unsafe { attr.__bindgen_anon_1.localityDomainOrdinal },
199            memory_type: attr.type_.try_into()?,
200            device: attr.device,
201            // SAFETY: `DevicePtr` only records the CUDA-reported alias; each use carries its own contract.
202            device_pointer: unsafe { DevicePtr::from_raw(attr.devicePointer.cast()) },
203            host_pointer: attr.hostPointer.cast(),
204        })
205    }
206}
207
208impl PointerAttributes {
209    /// Returns the CUDA pointer attributes for a raw pointer.
210    ///
211    /// # Errors
212    ///
213    /// Returns an error if CUDA cannot query attributes for `ptr`, `ptr` is not known to a unified-addressing context, or CUDA reports runtime initialization diagnostics.
214    pub fn query<T>(ptr: *const T) -> Result<Self> {
215        let mut attr_ffi = runtime::cudaPointerAttributes::default();
216        // SAFETY: `cudaPointerGetAttributes` only queries `ptr` and writes into the local `attr_ffi`.
217        unsafe {
218            try_ffi!(runtime::cudaPointerGetAttributes(
219                &raw mut attr_ffi,
220                ptr.cast(),
221            ))?;
222        }
223        attr_ffi.try_into()
224    }
225
226    /// Returns CUDA pointer attributes for a raw CUDA device pointer wrapper.
227    ///
228    /// # Errors
229    ///
230    /// Returns an error if CUDA cannot query attributes for `ptr`, the pointer is not known to the current CUDA context, or CUDA reports runtime initialization diagnostics.
231    pub fn query_device(ptr: DevicePtr) -> Result<Self> {
232        Self::query(ptr.as_ptr())
233    }
234
235    /// Returns CUDA pointer attributes for a non-null host or device pointer.
236    ///
237    /// # Errors
238    ///
239    /// Returns an error if CUDA cannot query attributes for `ptr`, the pointer is not known to a unified-addressing context, or CUDA reports runtime initialization diagnostics.
240    pub fn query_non_null<T>(ptr: NonNull<T>) -> Result<Self> {
241        Self::query(ptr.as_ptr())
242    }
243}
244
245/// Specifies the type and identity of a memory location.
246#[derive(Debug, Default, Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
247#[non_exhaustive]
248pub enum MemoryLocation {
249    /// Location is unspecified; no preferred location for a managed memory pool.
250    #[default]
251    Unspecified,
252    /// Location is a device location; the payload is a device ordinal.
253    Device(i32),
254    /// Location is host memory.
255    Host,
256    /// Location is a host NUMA node; the payload is its identifier.
257    Numa(i32),
258    /// Location is the host NUMA node of the current thread.
259    NumaCurrent,
260    /// Location is not visible but the device is accessible.
261    Invisible,
262    /// Location is a portion of device memory, specified by the locality domain ID.
263    DeviceLocalityDomain {
264        /// Device ordinal containing the locality domain.
265        device_id: u8,
266        /// Locality domain identifier within the device.
267        locality_domain_id: u8,
268    },
269}
270
271impl From<driver::CUmemLocation> for MemoryLocation {
272    fn from(value: driver::CUmemLocation) -> Self {
273        // SAFETY: each arm reads the union field that the matched location type selects.
274        unsafe {
275            match value.type_ {
276                MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE => {
277                    Self::Device(value.__bindgen_anon_1.id)
278                }
279                MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST => Self::Host,
280                MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA => {
281                    Self::Numa(value.__bindgen_anon_1.id)
282                }
283                MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT => Self::NumaCurrent,
284                MemoryLocationKind::CU_MEM_LOCATION_TYPE_INVISIBLE => Self::Invisible,
285                MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN => {
286                    let location = value.__bindgen_anon_1.localized;
287                    Self::DeviceLocalityDomain {
288                        device_id: location.deviceId,
289                        locality_domain_id: location.localityDomainId,
290                    }
291                }
292                _ => Self::Unspecified,
293            }
294        }
295    }
296}
297
298impl From<MemoryLocation> for driver::CUmemLocation {
299    fn from(value: MemoryLocation) -> Self {
300        let mut raw = Self::default();
301        let (kind, id) = match value {
302            MemoryLocation::Unspecified => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_INVALID, 0),
303            MemoryLocation::Device(id) => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE, id),
304            MemoryLocation::Host => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST, 0),
305            MemoryLocation::Numa(id) => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA, id),
306            MemoryLocation::NumaCurrent => (
307                MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT,
308                0,
309            ),
310            MemoryLocation::Invisible => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_INVISIBLE, -2),
311            MemoryLocation::DeviceLocalityDomain {
312                device_id,
313                locality_domain_id,
314            } => {
315                raw.type_ = MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN;
316                raw.__bindgen_anon_1.localized =
317                    driver::CUmemLocation_st__bindgen_ty_1__bindgen_ty_1 {
318                        deviceId: device_id,
319                        localityDomainId: locality_domain_id,
320                    };
321                return raw;
322            }
323        };
324        raw.type_ = kind;
325        raw.__bindgen_anon_1.id = id;
326        raw
327    }
328}
329
330/// A page-locked host-memory range suitable for efficient CUDA transfers.
331///
332/// # Safety
333///
334/// Implementors must guarantee the range returned by [`HostSlice::as_host_ptr`] is page-locked for the lifetime of `&self`.
335/// [`Self::host_region`] must report that range, the actual registration flags, and the identity shared by all mapped aliases.
336pub unsafe trait PinnedHostSlice<T: DeviceRepr>: HostSlice<T> {
337    /// Describes the same bytes as this host slice, preserving identity across mapped aliases.
338    fn host_region(&self) -> HostRegion<'_>;
339}
340
341/// A mutable page-locked host-memory range suitable for efficient CUDA transfers.
342///
343/// # Safety
344///
345/// Implementors must uphold both [`PinnedHostSlice`] and [`HostSliceMut`] contracts.
346pub unsafe trait PinnedHostSliceMut<T: DeviceRepr>:
347    PinnedHostSlice<T> + HostSliceMut<T>
348{
349}
350
351unsafe fn free_host_raw(ptr: *mut ()) -> Result<()> {
352    // SAFETY: the caller passes a live `cudaMallocHost` block that nothing uses any more.
353    unsafe { try_ffi!(runtime::cudaFreeHost(ptr.cast())) }
354}
355
356unsafe fn register_host_raw(ptr: *mut (), size: usize, flags: HostRegisterFlags) -> Result<()> {
357    // SAFETY: the caller passes `size` live host bytes at `ptr` that stay allocated until unregistered.
358    unsafe {
359        try_ffi!(runtime::cudaHostRegister(
360            ptr.cast(),
361            size as _,
362            flags.bits()
363        ))?;
364    }
365    Ok(())
366}
367
368unsafe fn unregister_host_raw(ptr: *mut ()) -> Result<()> {
369    // SAFETY: the caller passes the base of a live registration that no queued work still uses.
370    unsafe { try_ffi!(runtime::cudaHostUnregister(ptr.cast())) }
371}
372
373/// Retrieves memory location information for an address range.
374///
375/// Returns the most common location in each summary region, sampling at the specified interval.
376/// A zero sampling granularity uses the system default.
377///
378/// # Safety
379///
380/// The range must remain allocated throughout this call and refer to managed memory or system-allocated pageable memory not registered with CUDA.
381///
382/// # Errors
383///
384/// Returns an error if summary granularity is zero or exceeds the range size, sampling granularity exceeds summary granularity, the driver entry point is unavailable, or CUDA rejects the location query.
385pub unsafe fn location_info(
386    ptr: DevicePtr,
387    size: usize,
388    summary_granularity: usize,
389    sampling_granularity: usize,
390) -> Result<Vec<MemoryLocation>> {
391    if summary_granularity == 0 {
392        return Err(Error::not_positive("summary granularity"));
393    }
394
395    if summary_granularity > size {
396        return Err(Error::out_of_range("summary granularity"));
397    }
398
399    if sampling_granularity > summary_granularity {
400        return Err(Error::out_of_range("sampling granularity"));
401    }
402
403    let count = size.div_ceil(summary_granularity);
404    let mut locations = vec![driver::CUmemLocation::default(); count];
405    let address = to_u64(ptr.addr(), "device address")?;
406    // SAFETY: the caller keeps the range allocated, and `locations` has one writable entry per summary region.
407    unsafe {
408        cuMemGetLocationInfo(
409            address,
410            size as _,
411            summary_granularity as _,
412            sampling_granularity as _,
413            locations.as_mut_ptr(),
414        )?;
415    }
416    Ok(locations.into_iter().map(Into::into).collect())
417}
418
419#[cfg(all(test, feature = "testing"))]
420mod tests;