Skip to main content

singe_cuda/graph/
memory.rs

1//! Graph nodes for stream memory synchronization.
2
3use std::ptr;
4
5use singe_cuda_sys::driver as sys;
6
7use crate::{
8    error::Result,
9    graph::{ExecutableGraph, Graph, GraphNode},
10    stream::memory::{MemoryOperation, native_batch},
11    try_ffi,
12    utility::{to_u32, to_u64},
13};
14
15impl Graph {
16    /// Adds a batch memory-operation node to this graph.
17    ///
18    /// # Safety
19    ///
20    /// Follow [`crate::stream::Stream::memory_operations`]'s address and progress contracts for every replay.
21    ///
22    /// # Errors
23    ///
24    /// Returns `Error::OutOfRange` for 256 or more operations, `Error::NullPointer` for null wait or write addresses, or `Error::Misaligned` for misaligned ones.
25    /// Also returns an error for a dependency from another graph, an unrepresentable dependency count, or CUDA rejecting batch-node creation.
26    pub unsafe fn add_memory_operations_node(
27        &mut self,
28        dependencies: &[GraphNode],
29        operations: &[MemoryOperation],
30    ) -> Result<GraphNode> {
31        self.check_nodes(dependencies)?;
32        let context = self.context();
33        let mut native = native_batch(operations)?;
34        let params = batch_params(context.as_raw(), &mut native)?;
35        let dependencies: Vec<_> = dependencies.iter().map(GraphNode::as_raw).collect();
36        let mut node = ptr::null_mut();
37        // SAFETY: `node` is a local output, `check_nodes` confirmed the dependencies belong to this exclusively borrowed graph, `native_batch` validated the operations in `native`, which `params` points into and which outlives the call, and the caller keeps the addresses valid for every replay.
38        unsafe {
39            try_ffi!(sys::cuGraphAddBatchMemOpNode(
40                &raw mut node,
41                self.as_raw(),
42                dependencies.as_ptr(),
43                to_u64(dependencies.len(), "graph dependency count")?,
44                &raw const params
45            ))?;
46        }
47        Ok(self.node_from_raw(node))
48    }
49
50    /// Replaces an existing batch node's operations.
51    ///
52    /// # Safety
53    ///
54    /// The new addresses and synchronization must satisfy the replay contract of [`Self::add_memory_operations_node`].
55    ///
56    /// # Errors
57    ///
58    /// Returns `Error::OutOfRange` for 256 or more operations, `Error::NullPointer` for null wait or write addresses, or `Error::Misaligned` for misaligned ones.
59    /// Also returns an error if the node belongs to another graph or CUDA rejects the new batch parameters.
60    pub unsafe fn set_memory_operations_node(
61        &mut self,
62        node: &GraphNode,
63        operations: &[MemoryOperation],
64    ) -> Result<()> {
65        self.check_node(node)?;
66        let context = self.context();
67        let mut native = native_batch(operations)?;
68        let params = batch_params(context.as_raw(), &mut native)?;
69        // SAFETY: `check_node` confirmed `node` belongs to this exclusively borrowed graph, `native_batch` validated the operations in `native`, which outlives the call, and the caller keeps the new addresses valid for every replay.
70        unsafe {
71            try_ffi!(sys::cuGraphBatchMemOpNodeSetParams(
72                node.as_raw(),
73                &raw const params
74            ))
75        }
76    }
77}
78
79impl ExecutableGraph {
80    /// Replaces a batch node's addresses, values and wait comparisons in this executable.
81    /// Operation count, kinds, context, barriers and flush flags must remain unchanged.
82    ///
83    /// # Safety
84    ///
85    /// Keep replacement storage live and uphold synchronization for all subsequent launches.
86    ///
87    /// # Errors
88    ///
89    /// Returns `Error::OutOfRange` for 256 or more operations, `Error::NullPointer` for null wait or write addresses, or `Error::Misaligned` for misaligned ones.
90    /// Also returns an error if the node does not belong to the executable's source graph or CUDA rejects the executable update, including changes forbidden for an existing batch node.
91    pub unsafe fn set_memory_operations_node(
92        &mut self,
93        node: &GraphNode,
94        operations: &[MemoryOperation],
95    ) -> Result<()> {
96        self.check_node(node)?;
97        let context = self.context();
98        let mut native = native_batch(operations)?;
99        let params = batch_params(context.as_raw(), &mut native)?;
100        // SAFETY: `self` owns the live executable, `check_node` confirmed `node` comes from its source graph, `native_batch` validated the operations in `native`, which outlives the call, and the caller keeps the new addresses valid for every later launch.
101        unsafe {
102            try_ffi!(sys::cuGraphExecBatchMemOpNodeSetParams(
103                self.as_raw(),
104                node.as_raw(),
105                &raw const params
106            ))
107        }
108    }
109}
110
111fn batch_params(
112    context: sys::CUcontext,
113    operations: &mut [sys::CUstreamBatchMemOpParams],
114) -> Result<sys::CUDA_BATCH_MEM_OP_NODE_PARAMS> {
115    Ok(sys::CUDA_BATCH_MEM_OP_NODE_PARAMS {
116        ctx: context,
117        count: to_u32(operations.len(), "stream memory operation count")?,
118        paramArray: operations.as_mut_ptr(),
119        flags: 0,
120    })
121}