Skip to main content

singe_cuda/stream/
memory.rs

1//! Stream memory synchronization using CUDA-visible device addresses.
2//!
3//! These operations do not establish CUDA scheduler dependencies.
4//! Express producer/consumer order with events as well to avoid scheduler deadlocks.
5//! Managed allocations are unsupported; registered host memory needs its mapped device address.
6
7use std::fmt;
8
9use bitflags::parser;
10use singe_cuda_sys::driver as sys;
11
12use crate::{
13    error::{Error, Result},
14    graph::owned::{Recordable, Recording},
15    stream::Stream,
16    submission::{DeviceOperation, Execution, Operation, Resources},
17    try_ffi,
18    types::DevicePtr,
19    utility::{check_address, driver_enum, to_u32, to_u64},
20};
21
22driver_enum! {
23    /// Condition used when a stream waits on a 32-bit or 64-bit memory value.
24    pub enum WaitCondition: sys::CUstreamWaitValue_flags {
25        /// Cyclic signed comparison: `(signed)(current - value) >= 0`.
26        GreaterOrEqual = CU_STREAM_WAIT_VALUE_GEQ,
27        /// Wait until \*addr == value.
28        Equal = CU_STREAM_WAIT_VALUE_EQ,
29        /// Wait until (\*addr & value) != 0.
30        And = CU_STREAM_WAIT_VALUE_AND,
31        /// Wait until ~(\*addr | value) != 0.
32        ///
33        /// [`DeviceAttribute::CanUseStreamWaitValueNor`](crate::device::DeviceAttribute::CanUseStreamWaitValueNor) reports whether a device supports it.
34        Nor = CU_STREAM_WAIT_VALUE_NOR,
35    }
36}
37
38bitflags::bitflags! {
39    /// Flags for 32-bit and 64-bit stream wait-value operations.
40    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
41    pub struct WaitFlags: u32 {
42        /// Follow the wait operation with a flush of outstanding remote writes.
43        ///
44        /// This means that, if a remote write operation is guaranteed to have reached the device before the wait can be satisfied, that write is guaranteed to be visible to downstream device work.
45        /// The device is permitted to reorder remote writes internally.
46        /// For example, this flag would be required if two remote writes arrive in a defined order, the wait is satisfied by the second write, and downstream work needs to observe the first write.
47        /// Only selected platforms support it, as [`DeviceAttribute::CanFlushRemoteWrites`](crate::device::DeviceAttribute::CanFlushRemoteWrites) reports.
48        const FLUSH_REMOTE_WRITES = sys::CUstreamWaitValue_flags::CU_STREAM_WAIT_VALUE_FLUSH.0;
49    }
50}
51
52impl fmt::Display for WaitFlags {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        parser::to_writer(self, f)
55    }
56}
57
58/// Scope of a barrier in a CUDA stream memory-operation batch.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum MemoryBarrierScope {
61    /// Uses a system-scoped memory barrier.
62    System,
63    /// Uses a GPU-scoped memory barrier.
64    Device,
65}
66
67/// One ordered memory operation; addresses are borrowed and confer no access permission.
68#[derive(Debug, Clone, Copy)]
69#[non_exhaustive]
70pub enum MemoryOperation {
71    /// Waits for a 32-bit device word to satisfy the selected comparison.
72    Wait32 {
73        /// Address of the device word; must be nonnull and aligned to 4 bytes.
74        address: DevicePtr,
75        /// 32-bit reference value used by `condition`.
76        value: u32,
77        /// Comparison of the current device word against `value`.
78        condition: WaitCondition,
79        /// Additional remote-write visibility behavior after the wait.
80        flags: WaitFlags,
81    },
82    /// Waits for a 64-bit device word to satisfy the selected comparison.
83    Wait64 {
84        /// Address of the device word; must be nonnull and aligned to 8 bytes.
85        address: DevicePtr,
86        /// 64-bit reference value used by `condition`.
87        value: u64,
88        /// Comparison of the current device word against `value`.
89        condition: WaitCondition,
90        /// Additional remote-write visibility behavior after the wait.
91        flags: WaitFlags,
92    },
93    /// Writes a 32-bit device word with the native stream memory fence enabled.
94    Write32 {
95        /// Device destination address; must be nonnull and aligned to 4 bytes.
96        address: DevicePtr,
97        /// 32-bit value written to the device word.
98        value: u32,
99    },
100    /// Writes a 64-bit device word with the native stream memory fence enabled.
101    Write64 {
102        /// Device destination address; must be nonnull and aligned to 8 bytes.
103        address: DevicePtr,
104        /// 64-bit value written to the device word.
105        value: u64,
106    },
107    /// Enqueues a memory barrier with the selected scope.
108    Barrier(MemoryBarrierScope),
109    /// Flushes outstanding remote writes so they are visible to downstream device work.
110    FlushRemoteWrites,
111}
112
113impl MemoryOperation {
114    pub(crate) fn native(self) -> Result<sys::CUstreamBatchMemOpParams> {
115        use sys::CUstreamBatchMemOpType as Kind;
116        let mut raw = sys::CUstreamBatchMemOpParams::default();
117        match self {
118            Self::Wait32 {
119                address,
120                value,
121                condition,
122                flags,
123            } => {
124                check_address(address, 4)?;
125                raw.waitValue.operation = Kind::CU_STREAM_MEM_OP_WAIT_VALUE_32;
126                raw.waitValue.address = to_u64(address.addr(), "memory operation address")?;
127                raw.waitValue.__bindgen_anon_1.value = value;
128                raw.waitValue.flags = u32::from(condition) | flags.bits();
129            }
130            Self::Wait64 {
131                address,
132                value,
133                condition,
134                flags,
135            } => {
136                check_address(address, 8)?;
137                raw.waitValue.operation = Kind::CU_STREAM_MEM_OP_WAIT_VALUE_64;
138                raw.waitValue.address = to_u64(address.addr(), "memory operation address")?;
139                raw.waitValue.__bindgen_anon_1.value64 = value;
140                raw.waitValue.flags = u32::from(condition) | flags.bits();
141            }
142            Self::Write32 { address, value } => {
143                check_address(address, 4)?;
144                raw.writeValue.operation = Kind::CU_STREAM_MEM_OP_WRITE_VALUE_32;
145                raw.writeValue.address = to_u64(address.addr(), "memory operation address")?;
146                raw.writeValue.__bindgen_anon_1.value = value;
147            }
148            Self::Write64 { address, value } => {
149                check_address(address, 8)?;
150                raw.writeValue.operation = Kind::CU_STREAM_MEM_OP_WRITE_VALUE_64;
151                raw.writeValue.address = to_u64(address.addr(), "memory operation address")?;
152                raw.writeValue.__bindgen_anon_1.value64 = value;
153            }
154            Self::Barrier(scope) => {
155                raw.memoryBarrier.operation = Kind::CU_STREAM_MEM_OP_BARRIER;
156                raw.memoryBarrier.flags = match scope {
157                    MemoryBarrierScope::System => {
158                        sys::CUstreamMemoryBarrier_flags::CU_STREAM_MEMORY_BARRIER_TYPE_SYS.0
159                    }
160                    MemoryBarrierScope::Device => {
161                        sys::CUstreamMemoryBarrier_flags::CU_STREAM_MEMORY_BARRIER_TYPE_GPU.0
162                    }
163                };
164            }
165            Self::FlushRemoteWrites => {
166                raw.flushRemoteWrites.operation = Kind::CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES;
167            }
168        }
169        Ok(raw)
170    }
171}
172
173pub(crate) fn native_batch(
174    operations: &[MemoryOperation],
175) -> Result<Vec<sys::CUstreamBatchMemOpParams>> {
176    // CUDA's batch count is strictly less than 256, including graph nodes.
177    if operations.len() >= 256 {
178        return Err(Error::out_of_range("stream memory operation count"));
179    }
180    operations
181        .iter()
182        .copied()
183        .map(MemoryOperation::native)
184        .collect()
185}
186
187impl Stream {
188    /// Enqueues an ordered batch of at most 255 memory operations.
189    ///
190    /// # Safety
191    ///
192    /// Addresses must be live, naturally aligned, non-managed memory accessible in this context.
193    /// Keep storage live and exclude conflicting accesses until completion or every captured replay.
194    /// Waits must be satisfiable without circular dependencies, with event ordering visible to CUDA.
195    ///
196    /// # Errors
197    ///
198    /// Returns `Error::OutOfRange` for 256 or more operations, `Error::NullPointer` for a null wait or write address, or `Error::Misaligned` for a misaligned one.
199    /// Also propagates context binding and native batch errors, including unsupported operations or device capabilities.
200    /// An empty batch succeeds without binding the context or calling CUDA.
201    pub unsafe fn memory_operations(&self, operations: &[MemoryOperation]) -> Result<()> {
202        let mut native = native_batch(operations)?;
203        // SAFETY: `native_batch` checked the count, nullness, and alignment, and the caller guarantees the addresses' liveness, access exclusion, and progress.
204        unsafe { self.enqueue_memory_operations(&mut native) }
205    }
206
207    // The batch is validated on construction; CUDA copies the descriptors during this call.
208    unsafe fn enqueue_memory_operations(
209        &self,
210        native: &mut [sys::CUstreamBatchMemOpParams],
211    ) -> Result<()> {
212        if native.is_empty() {
213            return Ok(());
214        }
215
216        self.context().bind()?;
217        // SAFETY: the stream is live in the context bound above, and `native` holds the validated descriptors CUDA copies during the call; the caller guarantees the addressed storage.
218        unsafe {
219            try_ffi!(sys::cuStreamBatchMemOp_v2(
220                self.as_raw(),
221                to_u32(native.len(), "stream memory operation count")?,
222                native.as_mut_ptr(),
223                0
224            ))
225        }
226    }
227}
228
229macro_rules! word_operations {
230    ($wait:ident, $write:ident, $word:ty, $native_wait:ident, $native_write:ident) => {
231        impl Stream {
232            /// Waits for a naturally aligned device word to satisfy the condition.
233            ///
234            /// # Safety
235            ///
236            /// Follow [`Stream::memory_operations`]'s storage, ordering and progress requirements.
237            ///
238            /// # Errors
239            ///
240            /// Returns `Error::NullPointer` for a null address, or `Error::Misaligned` for one not aligned to the native word size.
241            /// Also propagates context binding and native wait errors for unsupported conditions, flags, or device capabilities.
242            pub unsafe fn $wait(
243                &self,
244                address: DevicePtr,
245                value: $word,
246                condition: WaitCondition,
247                flags: WaitFlags,
248            ) -> Result<()> {
249                check_address(address, size_of::<$word>())?;
250                self.context().bind()?;
251                // SAFETY: the address is checked non-null and aligned above, the stream is live in the bound context, and the caller guarantees the word's liveness and that the wait can be satisfied.
252                unsafe {
253                    try_ffi!(sys::$native_wait(
254                        self.as_raw(),
255                        to_u64(address.addr(), "memory operation address")?,
256                        value,
257                        u32::from(condition) | flags.bits()
258                    ))
259                }
260            }
261
262            /// Writes a naturally aligned device word with the native stream memory fence.
263            ///
264            /// # Safety
265            ///
266            /// Follow [`Stream::memory_operations`]'s storage and ordering requirements.
267            ///
268            /// # Errors
269            ///
270            /// Returns `Error::NullPointer` for a null address, or `Error::Misaligned` for one not aligned to the native word size.
271            /// Also propagates context binding and native write errors, including unsupported memory operations on the device.
272            pub unsafe fn $write(&self, address: DevicePtr, value: $word) -> Result<()> {
273                check_address(address, size_of::<$word>())?;
274                self.context().bind()?;
275                // SAFETY: the address is checked non-null and aligned above, the stream is live in the bound context, and the caller guarantees the word's liveness and access exclusion.
276                unsafe {
277                    try_ffi!(sys::$native_write(
278                        self.as_raw(),
279                        to_u64(address.addr(), "memory operation address")?,
280                        value,
281                        0
282                    ))
283                }
284            }
285        }
286    };
287}
288
289word_operations!(
290    wait_value32,
291    write_value32,
292    u32,
293    cuStreamWaitValue32_v2,
294    cuStreamWriteValue32_v2
295);
296
297word_operations!(
298    wait_value64,
299    write_value64,
300    u64,
301    cuStreamWaitValue64_v2,
302    cuStreamWriteValue64_v2
303);
304
305/// Prepared memory operations using the common resource ledger for submission or capture.
306pub struct MemoryOperations {
307    operations: Vec<sys::CUstreamBatchMemOpParams>,
308    resources: Resources,
309}
310
311impl fmt::Debug for MemoryOperations {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        f.debug_struct("MemoryOperations")
314            .field("operation_count", &self.operations.len())
315            .field("resources", &self.resources)
316            .finish()
317    }
318}
319
320impl MemoryOperations {
321    /// Validates a batch and binds its retained owners and access declarations.
322    ///
323    /// # Safety
324    ///
325    /// Resources must retain all referenced storage and declare every access.
326    /// Uphold [`Stream::memory_operations`]'s progress and native memory restrictions.
327    ///
328    /// # Errors
329    ///
330    /// Returns `Error::OutOfRange` for 256 or more operations, `Error::NullPointer` for a null wait or write address, or `Error::Misaligned` for a misaligned one.
331    /// Resource ownership, access declarations, and progress guarantees remain the caller's responsibility; no native work is enqueued during construction.
332    pub unsafe fn create(operations: &[MemoryOperation], resources: Resources) -> Result<Self> {
333        Ok(Self {
334            operations: native_batch(operations)?,
335            resources,
336        })
337    }
338}
339
340// SAFETY: `create`'s caller declared every owner and access in `resources`, which `enqueue` registers through `Execution::enqueue` before the batch, and the pending output is `()`.
341unsafe impl Operation for MemoryOperations {
342    type Pending = ();
343
344    type Output = ();
345
346    fn enqueue(mut self, execution: &mut Execution) -> Result<()> {
347        // SAFETY: `resources` retain every addressed buffer, as `create` requires, and the batch runs on the stream that orders those accesses.
348        unsafe {
349            execution.enqueue(self.resources, |stream| {
350                stream.enqueue_memory_operations(&mut self.operations)
351            })
352        }
353    }
354
355    unsafe fn resolve(pending: ()) -> Result<()> {
356        Ok(pending)
357    }
358}
359
360// SAFETY: `resolve` returns its `()` input unchanged, and `enqueue` schedules the whole batch without host resolution.
361unsafe impl DeviceOperation for MemoryOperations {}
362
363// SAFETY: `record` registers the declared owners and accesses with `Recording` before recording the batch, which needs no allocation or host wait.
364unsafe impl Recordable for MemoryOperations {
365    type Output = ();
366
367    fn record(mut self, recording: &mut Recording) -> Result<()> {
368        // SAFETY: `resources` retain every addressed buffer for every replay, as `create` requires, and the batch records on the capturing stream.
369        unsafe {
370            recording.enqueue(self.resources, |stream| {
371                stream.enqueue_memory_operations(&mut self.operations)
372            })
373        }
374    }
375}