1pub 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
63 #[repr(u32)]
64 #[non_exhaustive]
65 pub enum MemoryCopyKind: runtime::cudaMemcpyKind {
66 HostToHost = cudaMemcpyHostToHost,
68 HostToDevice = cudaMemcpyHostToDevice,
70 DeviceToHost = cudaMemcpyDeviceToHost,
72 DeviceToDevice = cudaMemcpyDeviceToDevice,
74 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90#[repr(transparent)]
91pub struct ArrayHandle(runtime::cudaArray_t);
92
93impl ArrayHandle {
94 pub const unsafe fn from_raw(handle: runtime::cudaArray_t) -> Self {
101 Self(handle)
102 }
103
104 #[must_use]
106 pub const fn as_raw(self) -> runtime::cudaArray_t {
107 self.0
108 }
109}
110
111bitflags::bitflags! {
112 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114 pub struct MemoryAttachFlags: u32 {
115 const GLOBAL = driver::CUmemAttach_flags::CU_MEM_ATTACH_GLOBAL.0;
117 const HOST = driver::CUmemAttach_flags::CU_MEM_ATTACH_HOST.0;
119 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
133 pub struct HostRegisterFlags: u32 {
134 const DEFAULT = runtime::cudaHostRegisterDefault;
136 const PORTABLE = runtime::cudaHostRegisterPortable;
138 const MAPPED = runtime::cudaHostRegisterMapped;
140 const IO_MEMORY = runtime::cudaHostRegisterIoMemory;
142 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
156 #[repr(u32)]
157 #[non_exhaustive]
158 pub enum MemoryType: runtime::cudaMemoryType {
159 Unregistered = cudaMemoryTypeUnregistered,
161 Host = cudaMemoryTypeHost,
163 Device = cudaMemoryTypeDevice,
165 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179pub struct PointerAttributes {
180 pub memory_type: MemoryType,
182 pub device: i32,
184 pub device_pointer: DevicePtr,
186 pub host_pointer: *mut (),
188 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 locality_domain_ordinal: unsafe { attr.__bindgen_anon_1.localityDomainOrdinal },
199 memory_type: attr.type_.try_into()?,
200 device: attr.device,
201 device_pointer: unsafe { DevicePtr::from_raw(attr.devicePointer.cast()) },
203 host_pointer: attr.hostPointer.cast(),
204 })
205 }
206}
207
208impl PointerAttributes {
209 pub fn query<T>(ptr: *const T) -> Result<Self> {
215 let mut attr_ffi = runtime::cudaPointerAttributes::default();
216 unsafe {
218 try_ffi!(runtime::cudaPointerGetAttributes(
219 &raw mut attr_ffi,
220 ptr.cast(),
221 ))?;
222 }
223 attr_ffi.try_into()
224 }
225
226 pub fn query_device(ptr: DevicePtr) -> Result<Self> {
232 Self::query(ptr.as_ptr())
233 }
234
235 pub fn query_non_null<T>(ptr: NonNull<T>) -> Result<Self> {
241 Self::query(ptr.as_ptr())
242 }
243}
244
245#[derive(Debug, Default, Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
247#[non_exhaustive]
248pub enum MemoryLocation {
249 #[default]
251 Unspecified,
252 Device(i32),
254 Host,
256 Numa(i32),
258 NumaCurrent,
260 Invisible,
262 DeviceLocalityDomain {
264 device_id: u8,
266 locality_domain_id: u8,
268 },
269}
270
271impl From<driver::CUmemLocation> for MemoryLocation {
272 fn from(value: driver::CUmemLocation) -> Self {
273 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
330pub unsafe trait PinnedHostSlice<T: DeviceRepr>: HostSlice<T> {
337 fn host_region(&self) -> HostRegion<'_>;
339}
340
341pub unsafe trait PinnedHostSliceMut<T: DeviceRepr>:
347 PinnedHostSlice<T> + HostSliceMut<T>
348{
349}
350
351unsafe fn free_host_raw(ptr: *mut ()) -> Result<()> {
352 unsafe { try_ffi!(runtime::cudaFreeHost(ptr.cast())) }
354}
355
356unsafe fn register_host_raw(ptr: *mut (), size: usize, flags: HostRegisterFlags) -> Result<()> {
357 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 unsafe { try_ffi!(runtime::cudaHostUnregister(ptr.cast())) }
371}
372
373pub 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 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;