pub mod array;
pub mod pattern;
pub mod peer;
mod allocation;
mod device;
mod managed;
mod pinned;
mod pitched;
mod pool;
mod registered;
mod stream_ordered;
pub mod transfer;
use std::{
fmt::{self, Display, Formatter},
ptr::NonNull,
};
use bitflags::parser;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use singe_core::impl_enum_display;
use singe_cuda_sys::{
driver::{self, CUmemLocationType as MemoryLocationKind},
runtime,
};
pub use self::{
allocation::DeviceAllocation,
device::{DeviceMemory, RawDeviceMemory},
managed::{ManagedMemory, RawManagedMemory},
pinned::{PinnedHost, PinnedStats, PinnedVec, PinnedVecExt},
pitched::{
PitchedDeviceMemory, PitchedDeviceVolume, RawPitchedDeviceMemory, RawPitchedDeviceVolume,
},
pool::{
MemoryAccessDescriptor, MemoryAccessFlag, MemoryAllocationType, MemoryPool,
MemoryPoolAttribute, MemoryPoolAttributeValue, MemoryPoolProps, MemoryPoolUsage,
RawMemoryPool,
},
registered::{RegisteredHostMemory, RegisteredHostSlice},
stream_ordered::StreamOrderedFree,
};
pub(crate) use self::{
allocation::{DeferredFree, DeviceDeallocation},
pinned::PinnedPool,
registered::mapped_host_device_ptr,
};
use crate::{
driver::entry_points::cuMemGetLocationInfo,
error::{Error, Result},
try_ffi,
types::DevicePtr,
utility::to_u64,
view::{DeviceRepr, HostRegion, HostSlice, HostSliceMut},
};
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum MemoryCopyKind: runtime::cudaMemcpyKind {
HostToHost = cudaMemcpyHostToHost,
HostToDevice = cudaMemcpyHostToDevice,
DeviceToHost = cudaMemcpyDeviceToHost,
DeviceToDevice = cudaMemcpyDeviceToDevice,
Default = cudaMemcpyDefault,
}
}
impl_enum_display!(MemoryCopyKind, {
Self::HostToHost => "cudaMemcpyHostToHost",
Self::HostToDevice => "cudaMemcpyHostToDevice",
Self::DeviceToHost => "cudaMemcpyDeviceToHost",
Self::DeviceToDevice => "cudaMemcpyDeviceToDevice",
Self::Default => "cudaMemcpyDefault",
});
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct ArrayHandle(runtime::cudaArray_t);
impl ArrayHandle {
pub const unsafe fn from_raw(handle: runtime::cudaArray_t) -> Self {
Self(handle)
}
#[must_use]
pub const fn as_raw(self) -> runtime::cudaArray_t {
self.0
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MemoryAttachFlags: u32 {
const GLOBAL = driver::CUmemAttach_flags::CU_MEM_ATTACH_GLOBAL.0;
const HOST = driver::CUmemAttach_flags::CU_MEM_ATTACH_HOST.0;
const SINGLE = driver::CUmemAttach_flags::CU_MEM_ATTACH_SINGLE.0;
}
}
impl Display for MemoryAttachFlags {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
parser::to_writer(self, f)
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HostRegisterFlags: u32 {
const DEFAULT = runtime::cudaHostRegisterDefault;
const PORTABLE = runtime::cudaHostRegisterPortable;
const MAPPED = runtime::cudaHostRegisterMapped;
const IO_MEMORY = runtime::cudaHostRegisterIoMemory;
const READ_ONLY = runtime::cudaHostRegisterReadOnly;
}
}
impl Display for HostRegisterFlags {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
parser::to_writer(self, f)
}
}
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum MemoryType: runtime::cudaMemoryType {
Unregistered = cudaMemoryTypeUnregistered,
Host = cudaMemoryTypeHost,
Device = cudaMemoryTypeDevice,
Managed = cudaMemoryTypeManaged,
}
}
impl_enum_display!(MemoryType, {
Self::Unregistered => "cudaMemoryTypeUnregistered",
Self::Host => "cudaMemoryTypeHost",
Self::Device => "cudaMemoryTypeDevice",
Self::Managed => "cudaMemoryTypeManaged",
});
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PointerAttributes {
pub memory_type: MemoryType,
pub device: i32,
pub device_pointer: DevicePtr,
pub host_pointer: *mut (),
pub locality_domain_ordinal: i32,
}
impl TryFrom<runtime::cudaPointerAttributes> for PointerAttributes {
type Error = Error;
fn try_from(attr: runtime::cudaPointerAttributes) -> Result<Self> {
Ok(Self {
locality_domain_ordinal: unsafe { attr.__bindgen_anon_1.localityDomainOrdinal },
memory_type: attr.type_.try_into()?,
device: attr.device,
device_pointer: unsafe { DevicePtr::from_raw(attr.devicePointer.cast()) },
host_pointer: attr.hostPointer.cast(),
})
}
}
impl PointerAttributes {
pub fn query<T>(ptr: *const T) -> Result<Self> {
let mut attr_ffi = runtime::cudaPointerAttributes::default();
unsafe {
try_ffi!(runtime::cudaPointerGetAttributes(
&raw mut attr_ffi,
ptr.cast(),
))?;
}
attr_ffi.try_into()
}
pub fn query_device(ptr: DevicePtr) -> Result<Self> {
Self::query(ptr.as_ptr())
}
pub fn query_non_null<T>(ptr: NonNull<T>) -> Result<Self> {
Self::query(ptr.as_ptr())
}
}
#[derive(Debug, Default, Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
#[non_exhaustive]
pub enum MemoryLocation {
#[default]
Unspecified,
Device(i32),
Host,
Numa(i32),
NumaCurrent,
Invisible,
DeviceLocalityDomain {
device_id: u8,
locality_domain_id: u8,
},
}
impl From<driver::CUmemLocation> for MemoryLocation {
fn from(value: driver::CUmemLocation) -> Self {
unsafe {
match value.type_ {
MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE => {
Self::Device(value.__bindgen_anon_1.id)
}
MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST => Self::Host,
MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA => {
Self::Numa(value.__bindgen_anon_1.id)
}
MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT => Self::NumaCurrent,
MemoryLocationKind::CU_MEM_LOCATION_TYPE_INVISIBLE => Self::Invisible,
MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN => {
let location = value.__bindgen_anon_1.localized;
Self::DeviceLocalityDomain {
device_id: location.deviceId,
locality_domain_id: location.localityDomainId,
}
}
_ => Self::Unspecified,
}
}
}
}
impl From<MemoryLocation> for driver::CUmemLocation {
fn from(value: MemoryLocation) -> Self {
let mut raw = Self::default();
let (kind, id) = match value {
MemoryLocation::Unspecified => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_INVALID, 0),
MemoryLocation::Device(id) => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE, id),
MemoryLocation::Host => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST, 0),
MemoryLocation::Numa(id) => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA, id),
MemoryLocation::NumaCurrent => (
MemoryLocationKind::CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT,
0,
),
MemoryLocation::Invisible => (MemoryLocationKind::CU_MEM_LOCATION_TYPE_INVISIBLE, -2),
MemoryLocation::DeviceLocalityDomain {
device_id,
locality_domain_id,
} => {
raw.type_ = MemoryLocationKind::CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN;
raw.__bindgen_anon_1.localized =
driver::CUmemLocation_st__bindgen_ty_1__bindgen_ty_1 {
deviceId: device_id,
localityDomainId: locality_domain_id,
};
return raw;
}
};
raw.type_ = kind;
raw.__bindgen_anon_1.id = id;
raw
}
}
pub unsafe trait PinnedHostSlice<T: DeviceRepr>: HostSlice<T> {
fn host_region(&self) -> HostRegion<'_>;
}
pub unsafe trait PinnedHostSliceMut<T: DeviceRepr>:
PinnedHostSlice<T> + HostSliceMut<T>
{
}
unsafe fn free_host_raw(ptr: *mut ()) -> Result<()> {
unsafe { try_ffi!(runtime::cudaFreeHost(ptr.cast())) }
}
unsafe fn register_host_raw(ptr: *mut (), size: usize, flags: HostRegisterFlags) -> Result<()> {
unsafe {
try_ffi!(runtime::cudaHostRegister(
ptr.cast(),
size as _,
flags.bits()
))?;
}
Ok(())
}
unsafe fn unregister_host_raw(ptr: *mut ()) -> Result<()> {
unsafe { try_ffi!(runtime::cudaHostUnregister(ptr.cast())) }
}
pub unsafe fn location_info(
ptr: DevicePtr,
size: usize,
summary_granularity: usize,
sampling_granularity: usize,
) -> Result<Vec<MemoryLocation>> {
if summary_granularity == 0 {
return Err(Error::not_positive("summary granularity"));
}
if summary_granularity > size {
return Err(Error::out_of_range("summary granularity"));
}
if sampling_granularity > summary_granularity {
return Err(Error::out_of_range("sampling granularity"));
}
let count = size.div_ceil(summary_granularity);
let mut locations = vec![driver::CUmemLocation::default(); count];
let address = to_u64(ptr.addr(), "device address")?;
unsafe {
cuMemGetLocationInfo(
address,
size as _,
summary_granularity as _,
sampling_granularity as _,
locations.as_mut_ptr(),
)?;
}
Ok(locations.into_iter().map(Into::into).collect())
}
#[cfg(all(test, feature = "testing"))]
mod tests;