singe_cuda/virtual_memory.rs
1//! Virtual address reservations, physical allocations and mappings.
2
3use std::{
4 mem::ManuallyDrop,
5 os::fd::{BorrowedFd, OwnedFd},
6 ptr,
7 result::Result as StdResult,
8 sync::Arc,
9};
10
11use bitflags::bitflags;
12use singe_core::report_cleanup_failure;
13use singe_cuda_sys::driver as sys;
14
15use crate::{
16 context::Context,
17 error::{Error, Result},
18 memory::{MemoryAccessDescriptor, MemoryAccessFlag, MemoryLocation},
19 try_ffi,
20 types::DevicePtr,
21 utility::{to_c_ulong, to_u32, to_usize, usage_bits},
22};
23
24bitflags! {
25 /// Available export handle types for an allocation or memory pool.
26 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27 pub struct AllocationHandleTypes: u32 {
28 /// Allows a file descriptor to represent the allocation for IPC.
29 const POSIX_FILE_DESCRIPTOR = sys::CUmemAllocationHandleType::CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR.0;
30 /// Allows a Win32 NT handle to represent the allocation for IPC.
31 const WIN32 = sys::CUmemAllocationHandleType::CU_MEM_HANDLE_TYPE_WIN32.0;
32 /// Allows a Win32 KMT handle to represent the allocation for IPC.
33 const WIN32_KMT = sys::CUmemAllocationHandleType::CU_MEM_HANDLE_TYPE_WIN32_KMT.0;
34 /// Allows a fabric handle to represent the allocation for IPC.
35 const FABRIC = sys::CUmemAllocationHandleType::CU_MEM_HANDLE_TYPE_FABRIC.0;
36 }
37 /// Usage restrictions of a physical allocation.
38 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
39 pub struct AllocationUsage: u16 {
40 /// Allocation will be used as a tile pool.
41 const TILE_POOL = usage_bits(sys::CU_MEM_CREATE_USAGE_TILE_POOL);
42 /// Allocation will be used for hardware decompression.
43 const HARDWARE_DECOMPRESSION = usage_bits(sys::CU_MEM_CREATE_USAGE_HW_DECOMPRESS);
44 /// Permits PCIe GPUDirect RDMA access; valid only when RDMA capability is set.
45 const GPU_DIRECT_RDMA_OVER_PCIE = usage_bits(sys::CU_MEM_CREATE_USAGE_GPU_DIRECT_RDMA_OVER_PCIE);
46 }
47}
48
49/// Specifies the allocation properties for an allocation.
50#[derive(Debug, Clone, Copy)]
51pub struct AllocationOptions {
52 /// Location of allocation.
53 pub location: MemoryLocation,
54 /// Handle types the allocation can be exported as; empty disables export.
55 pub handle_types: AllocationHandleTypes,
56 /// Allocating compressible memory.
57 pub compressible: bool,
58 /// Enables `GPUDirect` RDMA access to this allocation.
59 pub gpu_direct_rdma_capable: bool,
60 /// Bit mask indicating intended usage for this allocation.
61 pub usage: AllocationUsage,
62}
63
64impl AllocationOptions {
65 /// Selects an allocation location with export, compression, RDMA, and special usage disabled.
66 #[must_use]
67 pub fn new(location: MemoryLocation) -> Self {
68 Self {
69 location,
70 handle_types: AllocationHandleTypes::empty(),
71 compressible: false,
72 gpu_direct_rdma_capable: false,
73 usage: AllocationUsage::empty(),
74 }
75 }
76
77 fn raw(self) -> Result<sys::CUmemAllocationProp> {
78 if self
79 .usage
80 .contains(AllocationUsage::GPU_DIRECT_RDMA_OVER_PCIE)
81 && !self.gpu_direct_rdma_capable
82 {
83 return Err(Error::out_of_range("allocation usage"));
84 }
85 Ok(sys::CUmemAllocationProp {
86 type_: sys::CUmemAllocationType::CU_MEM_ALLOCATION_TYPE_PINNED,
87 requestedHandleTypes: sys::CUmemAllocationHandleType(self.handle_types.bits()),
88 location: self.location.into(),
89 allocFlags: sys::CUmemAllocationProp_st__bindgen_ty_1 {
90 compressionType: u8::from(self.compressible),
91 gpuDirectRDMACapable: u8::from(self.gpu_direct_rdma_capable),
92 usage: self.usage.bits(),
93 ..Default::default()
94 },
95 ..Default::default()
96 })
97 }
98
99 /// Calculates either the minimal or recommended allocation granularity.
100 ///
101 /// # Errors
102 ///
103 /// Returns an error if RDMA usage over PCI Express is selected without enabling RDMA capability, CUDA rejects the allocation properties, or the granularity does not fit `usize`.
104 pub fn granularity(self, recommended: bool) -> Result<usize> {
105 let mut size = 0;
106 let flag = if recommended {
107 sys::CUmemAllocationGranularity_flags::CU_MEM_ALLOC_GRANULARITY_RECOMMENDED
108 } else {
109 sys::CUmemAllocationGranularity_flags::CU_MEM_ALLOC_GRANULARITY_MINIMUM
110 };
111 // SAFETY: `size` is a local output, and the properties are a temporary that lives through the call.
112 unsafe {
113 try_ffi!(sys::cuMemGetAllocationGranularity(
114 &raw mut size,
115 &self.raw()?,
116 flag
117 ))?;
118 }
119 to_usize(size, "allocation granularity")
120 }
121}
122
123/// Raw ownership of a physical allocation reference and its context.
124///
125/// Release `handle` while `context` is alive, or re-adopt the value with [`Allocation::from_raw`].
126#[derive(Debug)]
127pub struct RawAllocation {
128 /// Native allocation reference.
129 pub handle: sys::CUmemGenericAllocationHandle,
130 /// Allocation size in bytes.
131 pub size: usize,
132 /// Context the allocation belongs to.
133 pub context: Arc<Context>,
134}
135
136/// Raw ownership of a reserved virtual address range and its context.
137///
138/// Free the range while `context` is alive, or re-adopt the value with [`AddressReservation::from_raw`].
139#[derive(Debug)]
140pub struct RawAddressReservation {
141 /// Base of the reserved range.
142 pub address: DevicePtr,
143 /// Range size in bytes.
144 pub size: usize,
145 /// Context the range belongs to.
146 pub context: Arc<Context>,
147}
148
149/// A physical allocation without a device or host mapping.
150#[derive(Debug)]
151pub struct Allocation {
152 handle: sys::CUmemGenericAllocationHandle,
153 size: usize,
154 context: Arc<Context>,
155}
156
157impl Allocation {
158 /// Creates a memory allocation on the target device specified by the properties.
159 ///
160 /// # Errors
161 ///
162 /// Returns an error if `size` is zero or not a multiple of the minimum allocation granularity, RDMA usage over PCI Express is selected without RDMA capability, the context cannot be bound, or CUDA cannot allocate the memory.
163 pub fn create(
164 context: &Arc<Context>,
165 size: usize,
166 options: AllocationOptions,
167 ) -> Result<Arc<Self>> {
168 context.bind()?;
169 let granularity = options.granularity(false)?;
170 if size == 0 {
171 return Err(Error::not_positive("size"));
172 }
173
174 if !size.is_multiple_of(granularity) {
175 return Err(Error::misaligned("size", granularity));
176 }
177
178 let mut handle = 0;
179 let native_size = to_c_ulong(size, "allocation size")?;
180 // SAFETY: `handle` is a local output, the properties are a temporary that lives through the call, and `context` is bound.
181 unsafe {
182 try_ffi!(sys::cuMemCreate(
183 &raw mut handle,
184 native_size,
185 &options.raw()?,
186 0
187 ))?;
188 }
189 Ok(Arc::new(Self {
190 handle,
191 size,
192 context: Arc::clone(context),
193 }))
194 }
195
196 /// Returns the borrowed native physical-allocation handle without retaining another native reference.
197 #[must_use]
198 pub fn as_raw(&self) -> sys::CUmemGenericAllocationHandle {
199 self.handle
200 }
201
202 /// Returns the physical allocation size in bytes.
203 #[must_use]
204 pub fn size(&self) -> usize {
205 self.size
206 }
207
208 /// Returns the retained context associated with this allocation reference.
209 #[must_use]
210 pub fn context(&self) -> &Arc<Context> {
211 &self.context
212 }
213
214 /// Takes ownership of an existing allocation reference.
215 ///
216 /// # Safety
217 ///
218 /// `raw.handle` must be a live allocation reference owned by the caller, with at least `raw.size` bytes, valid for `raw.context`.
219 ///
220 /// # Errors
221 ///
222 /// Returns an error if `raw.handle` or `raw.size` is zero.
223 pub unsafe fn from_raw(raw: RawAllocation) -> Result<Arc<Self>> {
224 if raw.handle == 0 {
225 return Err(Error::NullHandle);
226 }
227
228 if raw.size == 0 {
229 return Err(Error::not_positive("size"));
230 }
231 Ok(Arc::new(Self {
232 handle: raw.handle,
233 size: raw.size,
234 context: raw.context,
235 }))
236 }
237
238 /// Transfers the allocation reference, size and context to the caller.
239 ///
240 /// # Errors
241 ///
242 /// Returns an error holding the allocation unchanged if another owner, such as a mapping, still retains it.
243 pub fn into_raw(this: Arc<Self>) -> StdResult<RawAllocation, Arc<Self>> {
244 let owner = ManuallyDrop::new(Arc::try_unwrap(this)?);
245 Ok(RawAllocation {
246 handle: owner.handle,
247 size: owner.size,
248 // SAFETY: the owner is wrapped in `ManuallyDrop`, so this field moves out exactly once.
249 context: unsafe { ptr::read(&raw const owner.context) },
250 })
251 }
252
253 /// Exports the allocation as an opaque file descriptor.
254 ///
255 /// # Errors
256 ///
257 /// Returns an error if CUDA cannot export this allocation as a POSIX file descriptor, including when it was not created with the required export handle type.
258 /// The returned descriptor is owned by the caller.
259 #[cfg(unix)]
260 pub fn export_fd(&self) -> Result<OwnedFd> {
261 use std::os::fd::FromRawFd;
262 let mut fd = -1;
263 // SAFETY: `fd` is a local `c_int`, the type CUDA writes for a POSIX file descriptor handle, and `self` owns the live allocation.
264 unsafe {
265 try_ffi!(sys::cuMemExportToShareableHandle(
266 (&raw mut fd).cast(),
267 self.handle,
268 sys::CUmemAllocationHandleType::CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR,
269 0
270 ))?;
271 }
272 // SAFETY: on success CUDA returns a new open descriptor that nothing else owns.
273 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
274 }
275
276 /// Imports an allocation from an opaque file descriptor.
277 ///
278 /// # Safety
279 ///
280 /// `size` must be the size of the exported allocation.
281 /// The descriptor must refer to a CUDA allocation accessible in `context`.
282 ///
283 /// # Errors
284 ///
285 /// Returns an error if `size` is zero, the descriptor is negative, the context cannot be bound, or CUDA rejects the import.
286 /// The file descriptor stays borrowed; this method does not take its ownership.
287 #[cfg(unix)]
288 pub unsafe fn import_fd(
289 context: &Arc<Context>,
290 fd: BorrowedFd<'_>,
291 size: usize,
292 ) -> Result<Arc<Self>> {
293 use std::os::fd::AsRawFd;
294 if size == 0 {
295 return Err(Error::not_positive("size"));
296 }
297
298 context.bind()?;
299 let os_handle = ptr::without_provenance_mut(to_usize(fd.as_raw_fd(), "file descriptor")?);
300 let mut handle = 0;
301 // SAFETY: CUDA reads the descriptor value from the pointer-sized handle, `handle` is a local output, and the caller guarantees the descriptor names an allocation of `size` bytes accessible in `context`.
302 unsafe {
303 try_ffi!(sys::cuMemImportFromShareableHandle(
304 &raw mut handle,
305 os_handle,
306 sys::CUmemAllocationHandleType::CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR
307 ))?;
308 Self::from_raw(RawAllocation {
309 handle,
310 size,
311 context: Arc::clone(context),
312 })
313 }
314 }
315}
316
317impl Drop for Allocation {
318 fn drop(&mut self) {
319 // A handle whose context cannot be bound leaks rather than being released under another context.
320 // SAFETY: this wrapper owns the allocation reference, and mappings that use it retain this owner, so none is live.
321 let result = self
322 .context
323 .bind()
324 .and_then(|()| unsafe { try_ffi!(sys::cuMemRelease(self.handle)) });
325
326 if let Err(error) = result {
327 report_cleanup_failure("release", "cuda memory allocation handle", &error);
328 }
329 }
330}
331
332/// A reserved virtual address range, without backing memory.
333#[derive(Debug)]
334pub struct AddressReservation {
335 address: sys::CUdeviceptr,
336 size: usize,
337 context: Arc<Context>,
338}
339
340impl AddressReservation {
341 /// Reserves an address range with the specified size and alignment.
342 ///
343 /// # Errors
344 ///
345 /// Returns an error if `size` is zero, a nonzero `alignment` is not a power of two, the context cannot be bound, or CUDA cannot reserve the range.
346 /// An alignment of zero requests CUDA's default alignment.
347 pub fn create(context: &Arc<Context>, size: usize, alignment: usize) -> Result<Self> {
348 if size == 0 {
349 return Err(Error::not_positive("size"));
350 }
351
352 if alignment != 0 && !alignment.is_power_of_two() {
353 return Err(Error::out_of_range("alignment"));
354 }
355
356 context.bind()?;
357 let mut address = 0;
358 let native_size = to_c_ulong(size, "reservation size")?;
359 let native_alignment = to_c_ulong(alignment, "reservation alignment")?;
360 // SAFETY: `address` is a local output, and `context` is bound.
361 unsafe {
362 try_ffi!(sys::cuMemAddressReserve(
363 &raw mut address,
364 native_size,
365 native_alignment,
366 0,
367 0
368 ))?;
369 }
370 Ok(Self {
371 address,
372 size,
373 context: Arc::clone(context),
374 })
375 }
376
377 /// Takes ownership of a reserved virtual address range.
378 ///
379 /// # Safety
380 ///
381 /// The range must be live, uniquely owned, associated with `raw.context`, and unmapped.
382 ///
383 /// # Errors
384 ///
385 /// Returns an error if `raw.size` is zero or `raw.address` is null.
386 pub unsafe fn from_raw(raw: RawAddressReservation) -> Result<Self> {
387 if raw.size == 0 {
388 return Err(Error::not_positive("size"));
389 }
390
391 if raw.address.as_ptr().is_null() {
392 return Err(Error::null_pointer("address"));
393 }
394 Ok(Self {
395 address: raw.address.as_ptr().addr() as sys::CUdeviceptr,
396 size: raw.size,
397 context: raw.context,
398 })
399 }
400
401 /// Transfers the reserved range and context to the caller.
402 #[must_use]
403 pub fn into_raw(self) -> RawAddressReservation {
404 let owner = ManuallyDrop::new(self);
405 RawAddressReservation {
406 address: owner.address(),
407 size: owner.size,
408 // SAFETY: the owner is wrapped in `ManuallyDrop`, so this field moves out exactly once.
409 context: unsafe { ptr::read(&raw const owner.context) },
410 }
411 }
412
413 /// Returns the base of the reserved virtual address range.
414 ///
415 /// A reservation alone has no backing storage or memory-access permission.
416 #[must_use]
417 pub fn address(&self) -> DevicePtr {
418 // SAFETY: the address is the base of the range this reservation owns; `DevicePtr` claims no access to it.
419 unsafe { DevicePtr::from_raw(self.address as *mut ()) }
420 }
421
422 /// Returns the reserved address-range size in bytes.
423 #[must_use]
424 pub fn size(&self) -> usize {
425 self.size
426 }
427
428 /// Maps an allocation into the reserved virtual address range.
429 ///
430 /// # Errors
431 ///
432 /// Returns an error if the reservation and allocation belong to different contexts, `offset` plus the reservation size overflows or exceeds the allocation, the context cannot be bound, or CUDA rejects the mapping, such as for an offset off the allocation granularity.
433 /// The consumed reservation is released on failure.
434 pub fn map(self, allocation: Arc<Allocation>, offset: usize) -> Result<Mapping> {
435 if self.context.as_raw() != allocation.context.as_raw() {
436 return Err(Error::MemoryContextMismatch);
437 }
438
439 let end = offset
440 .checked_add(self.size)
441 .ok_or_else(|| Error::out_of_range("mapping end"))?;
442 if end > allocation.size {
443 return Err(Error::buffer_too_small(
444 "physical allocation",
445 end,
446 allocation.size,
447 ));
448 }
449
450 self.context.bind()?;
451 let native_size = to_c_ulong(self.size, "mapping size")?;
452 let native_offset = to_c_ulong(offset, "mapping offset")?;
453 // SAFETY: `self` owns the reserved range and `allocation` the physical memory, both in the bound context, and the mapped span lies inside the allocation, as checked above.
454 unsafe {
455 try_ffi!(sys::cuMemMap(
456 self.address,
457 native_size,
458 native_offset,
459 allocation.handle,
460 0
461 ))?;
462 }
463 Ok(Mapping {
464 reservation: self,
465 allocation,
466 })
467 }
468}
469
470impl Drop for AddressReservation {
471 fn drop(&mut self) {
472 // SAFETY: this wrapper owns the reserved range, and a mapping that used it consumed and unmapped it first.
473 let result = self.context.bind().and_then(|()| unsafe {
474 try_ffi!(sys::cuMemAddressFree(self.address, self.size as _))
475 });
476
477 if let Err(error) = result {
478 report_cleanup_failure("free", "cuda virtual address range", &error);
479 }
480 }
481}
482
483/// A mapping that retains both its virtual reservation and physical allocation.
484#[derive(Debug)]
485pub struct Mapping {
486 reservation: AddressReservation,
487 allocation: Arc<Allocation>,
488}
489
490impl Mapping {
491 /// Returns the mapped device virtual address.
492 ///
493 /// Set appropriate permissions with [`Self::set_access`] before device use, and keep this mapping alive through every queued access.
494 #[must_use]
495 pub fn address(&self) -> DevicePtr {
496 self.reservation.address()
497 }
498
499 /// Returns the mapped range size in bytes.
500 #[must_use]
501 pub fn size(&self) -> usize {
502 self.reservation.size
503 }
504
505 /// Borrows the physical allocation retained by this mapping.
506 #[must_use]
507 pub fn allocation(&self) -> &Arc<Allocation> {
508 &self.allocation
509 }
510
511 /// Sets the access flags for the mapped virtual address range.
512 ///
513 /// # Safety
514 ///
515 /// No operation may access the mapping while permissions are changed, and all queued uses must finish before this mapping is dropped.
516 ///
517 /// # Errors
518 ///
519 /// Returns an error if the size or descriptor count does not fit the native type, or CUDA rejects the target locations, access flags, mapped address range, or permission change.
520 /// The descriptors establish no Rust-side access permission or initialization claim.
521 pub unsafe fn set_access(&mut self, access: &[MemoryAccessDescriptor]) -> Result<()> {
522 let raw = access
523 .iter()
524 .copied()
525 .map(sys::CUmemAccessDesc::from)
526 .collect::<Vec<_>>();
527 let native_size = to_c_ulong(self.reservation.size, "mapping size")?;
528 let count = to_c_ulong(raw.len(), "access descriptor count")?;
529 // SAFETY: `self` owns the whole mapped range, `raw` holds `count` descriptors for the call, and the caller excludes concurrent access to the mapping.
530 unsafe {
531 try_ffi!(sys::cuMemSetAccess(
532 self.reservation.address,
533 native_size,
534 raw.as_ptr(),
535 count
536 ))
537 }
538 }
539
540 /// Returns the access flags for a location and the mapped address.
541 ///
542 /// # Errors
543 ///
544 /// Returns an error if CUDA cannot query the access flags, or they do not fit `u32` or name no [`MemoryAccessFlag`].
545 pub fn access(&self, location: MemoryLocation) -> Result<MemoryAccessFlag> {
546 let mut flags = 0;
547 // SAFETY: `flags` is a local output, the location is a temporary that lives through the call, and `self` owns the mapped address.
548 unsafe {
549 try_ffi!(sys::cuMemGetAccess(
550 &raw mut flags,
551 &location.into(),
552 self.reservation.address
553 ))?;
554 }
555
556 let flags = to_u32(flags, "memory access flags")?;
557 MemoryAccessFlag::try_from(flags).map_err(|_| Error::UnknownEnumValue {
558 name: "memory access flags".into(),
559 value: i64::from(flags),
560 })
561 }
562}
563
564impl Drop for Mapping {
565 fn drop(&mut self) {
566 // SAFETY: this wrapper owns the mapping, and the caller of `set_access` keeps queued uses from outliving it.
567 let result = self.reservation.context.bind().and_then(|()| unsafe {
568 try_ffi!(sys::cuMemUnmap(
569 self.reservation.address,
570 self.reservation.size as _
571 ))
572 });
573
574 if let Err(error) = result {
575 report_cleanup_failure("unmap", "cuda virtual memory", &error);
576 }
577 }
578}