Skip to main content

singe_cuda/
ipc.rs

1//! Interprocess CUDA memory and event handle exchange.
2
3use std::{
4    fmt::{self, Display, Formatter},
5    mem, ptr,
6};
7
8use bitflags::parser;
9use singe_core::report_cleanup_failure;
10use singe_cuda_sys::{driver, runtime};
11
12use crate::{
13    error::{Error, Result},
14    try_ffi,
15};
16
17bitflags::bitflags! {
18    /// Flags for [`IpcMemoryHandle::create_mapping`].
19    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20    pub struct IpcMemoryFlags: u32 {
21        /// Automatically enable peer access between remote devices as needed.
22        const LAZY_ENABLE_PEER_ACCESS = driver::CUipcMem_flags::CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS.0;
23    }
24}
25
26impl Display for IpcMemoryFlags {
27    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
28        parser::to_writer(self, f)
29    }
30}
31
32/// An opaque CUDA IPC event export token that can be copied between processes.
33///
34/// This token does not own the exporting event or an imported event handle.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub struct IpcEventHandle(runtime::cudaIpcEventHandle_t);
37
38impl IpcEventHandle {
39    /// Wraps an exported native IPC event token without importing the event.
40    ///
41    /// # Safety
42    ///
43    /// Any subsequent event import must use an unchanged token exported by CUDA for a live IPC-capable event.
44    /// Coordinate the exporting event's lifetime with every process importing or using it.
45    #[must_use]
46    pub const unsafe fn from_raw(handle: runtime::cudaIpcEventHandle_t) -> Self {
47        Self(handle)
48    }
49
50    /// Creates a zero-filled placeholder token.
51    ///
52    /// The result does not identify an exported event resource.
53    #[must_use]
54    pub const fn zeroed() -> Self {
55        // SAFETY: this plain C struct is valid when all bytes are zero.
56        unsafe { mem::zeroed() }
57    }
58
59    /// Returns a copy of the native IPC event token without importing or retaining its resource.
60    #[must_use]
61    pub const fn as_raw(&self) -> runtime::cudaIpcEventHandle_t {
62        self.0
63    }
64}
65
66/// An opaque CUDA IPC memory export token that can be copied between processes.
67///
68/// This token does not retain the exporting allocation or an imported mapping.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub struct IpcMemoryHandle(runtime::cudaIpcMemHandle_t);
71
72impl IpcMemoryHandle {
73    /// Wraps an exported native IPC memory token without opening a mapping.
74    ///
75    /// # Safety
76    ///
77    /// Any subsequent mapping must use an unchanged token exported by CUDA for a live IPC-capable allocation.
78    /// Keep that allocation live until every imported mapping has been closed and prevent conflicting accesses across processes.
79    #[must_use]
80    pub const unsafe fn from_raw(handle: runtime::cudaIpcMemHandle_t) -> Self {
81        Self(handle)
82    }
83
84    /// Creates a zero-filled placeholder token.
85    ///
86    /// The result does not identify an exported memory resource.
87    #[must_use]
88    pub const fn zeroed() -> Self {
89        // SAFETY: this plain C struct is valid when all bytes are zero.
90        unsafe { mem::zeroed() }
91    }
92
93    /// Returns a copy of the native IPC memory token without importing or retaining its resource.
94    #[must_use]
95    pub const fn as_raw(&self) -> runtime::cudaIpcMemHandle_t {
96        self.0
97    }
98
99    /// Maps memory exported from another process with [`DeviceMemory::ipc_handle`](crate::memory::DeviceMemory::ipc_handle) into the current device address space.
100    /// For contexts on different devices, [`IpcMemoryHandle::create_mapping`] can attempt to enable peer access between the devices as if [`Context::enable_peer_access`](crate::context::Context::enable_peer_access) had been called.
101    /// This behavior is controlled by [`IpcMemoryFlags::LAZY_ENABLE_PEER_ACCESS`].
102    /// [`Device::can_access_peer`](crate::device::Device::can_access_peer) can determine if a mapping is possible.
103    ///
104    /// [`IpcMemoryHandle::create_mapping`] can open handles to devices that may not be visible in the current process.
105    ///
106    /// Imported memory handles from each device in a given process may only be opened by one context per device per other process.
107    ///
108    /// If the memory handle has already been opened by the current context, the reference count on the handle is incremented by 1 and the existing device pointer is returned.
109    ///
110    /// Memory returned from [`IpcMemoryHandle::create_mapping`] must be freed with [`OpenedIpcMemory::close`].
111    ///
112    /// Calling [`DeviceMemory::free`](crate::memory::DeviceMemory::free) on an exported memory region before calling [`OpenedIpcMemory::close`] in the importing context results in undefined behavior.
113    ///
114    /// IPC is restricted to devices with support for unified addressing on Linux and Windows operating systems.
115    /// IPC on Windows is supported for compatibility, but is not recommended because it has a performance cost.
116    /// Check device IPC support through the device properties exposed by this crate, for example [`DeviceProperties::ipc_event_supported`](crate::device::DeviceProperties::ipc_event_supported).
117    ///
118    /// Additional CUDA diagnostics:
119    ///
120    /// * This call may also return [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`] if it initializes internal CUDA runtime state.
121    /// * Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
122    ///   [`crate::error::Status::NotPermitted`] may, but is not guaranteed to, be returned as a diagnostic in that case.
123    /// * No guarantees are made about the address returned.
124    ///   In particular, multiple processes may not receive the same address for the same handle.
125    ///
126    /// # Errors
127    ///
128    /// Returns an error if CUDA Runtime cannot open the IPC handle, if the current device cannot access the allocation, or if CUDA returns a null mapped pointer.
129    pub fn create_mapping<T>(self, flags: IpcMemoryFlags) -> Result<OpenedIpcMemory<T>> {
130        let mut dev_ptr = ptr::null_mut();
131        // SAFETY: `dev_ptr` is a writable local, and the token is passed by value; an invalid token is reported as an error.
132        unsafe {
133            try_ffi!(runtime::cudaIpcOpenMemHandle(
134                &raw mut dev_ptr,
135                self.as_raw(),
136                flags.bits()
137            ))?;
138        }
139
140        if dev_ptr.is_null() {
141            return Err(Error::NullHandle);
142        }
143
144        Ok(OpenedIpcMemory {
145            ptr: dev_ptr.cast(),
146        })
147    }
148}
149
150/// An imported device mapping of another process's CUDA allocation.
151///
152/// Dropping this wrapper attempts to close the mapping.
153/// It does not own the allocation in the exporting process.
154/// Finish every use of this mapping before closing or dropping it; the exporting process must keep its allocation alive until all imports close.
155#[derive(Debug)]
156pub struct OpenedIpcMemory<T> {
157    ptr: *mut T,
158}
159
160impl<T> OpenedIpcMemory<T> {
161    /// Returns the imported device address.
162    ///
163    /// No allocation length or host accessibility is established by this pointer, and it remains valid only while this mapping and the exporting allocation remain live.
164    #[must_use]
165    pub const fn as_ptr(&self) -> *mut T {
166        self.ptr
167    }
168
169    /// Decrements the reference count of the memory returned by [`IpcMemoryHandle::create_mapping`] by 1.
170    /// When the reference count reaches 0, this unmaps the memory.
171    /// The original allocation in the exporting process and imported mappings in other processes are unaffected.
172    ///
173    /// Resources used to enable peer access are freed if this is the last mapping using them.
174    ///
175    /// IPC is restricted to devices with support for unified addressing on Linux and Windows operating systems.
176    /// IPC on Windows is supported for compatibility, but is not recommended because it has a performance cost.
177    /// Check device IPC support through the device properties exposed by this crate, for example [`DeviceProperties::ipc_event_supported`](crate::device::DeviceProperties::ipc_event_supported).
178    ///
179    /// Additional CUDA diagnostics:
180    ///
181    /// * This call may also return [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`] if it initializes internal CUDA runtime state.
182    /// * Callbacks must not call CUDA functions; see [`Stream::add_callback`](crate::stream::Stream::add_callback).
183    ///   [`crate::error::Status::NotPermitted`] may, but is not guaranteed to, be returned as a diagnostic in that case.
184    ///
185    /// # Errors
186    ///
187    /// Returns an error if CUDA Runtime cannot close the imported mapping.
188    pub fn close(self) -> Result<()> {
189        let ptr: *mut () = self.ptr.cast();
190        mem::forget(self);
191        if ptr.is_null() {
192            return Ok(());
193        }
194        // SAFETY: `ptr` is the non-null mapping `cudaIpcOpenMemHandle` returned, and `mem::forget` above keeps `Drop` from closing it again.
195        unsafe { try_ffi!(runtime::cudaIpcCloseMemHandle(ptr.cast())) }
196    }
197}
198
199impl<T> Drop for OpenedIpcMemory<T> {
200    fn drop(&mut self) {
201        if self.ptr.is_null() {
202            return;
203        }
204
205        // SAFETY: `self.ptr` is the non-null mapping `cudaIpcOpenMemHandle` returned, closed only here since `close` forgets the owner.
206        if let Err(error) = unsafe { try_ffi!(runtime::cudaIpcCloseMemHandle(self.ptr.cast())) } {
207            report_cleanup_failure("close", "cuda ipc memory handle", &error);
208        }
209    }
210}