use std::fmt;
use bitflags::parser;
use singe_cuda_sys::driver as sys;
use crate::{
error::{Error, Result},
graph::owned::{Recordable, Recording},
stream::Stream,
submission::{DeviceOperation, Execution, Operation, Resources},
try_ffi,
types::DevicePtr,
utility::{check_address, driver_enum, to_u32, to_u64},
};
driver_enum! {
pub enum WaitCondition: sys::CUstreamWaitValue_flags {
GreaterOrEqual = CU_STREAM_WAIT_VALUE_GEQ,
Equal = CU_STREAM_WAIT_VALUE_EQ,
And = CU_STREAM_WAIT_VALUE_AND,
Nor = CU_STREAM_WAIT_VALUE_NOR,
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct WaitFlags: u32 {
const FLUSH_REMOTE_WRITES = sys::CUstreamWaitValue_flags::CU_STREAM_WAIT_VALUE_FLUSH.0;
}
}
impl fmt::Display for WaitFlags {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
parser::to_writer(self, f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MemoryBarrierScope {
System,
Device,
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum MemoryOperation {
Wait32 {
address: DevicePtr,
value: u32,
condition: WaitCondition,
flags: WaitFlags,
},
Wait64 {
address: DevicePtr,
value: u64,
condition: WaitCondition,
flags: WaitFlags,
},
Write32 {
address: DevicePtr,
value: u32,
},
Write64 {
address: DevicePtr,
value: u64,
},
Barrier(MemoryBarrierScope),
FlushRemoteWrites,
}
impl MemoryOperation {
pub(crate) fn native(self) -> Result<sys::CUstreamBatchMemOpParams> {
use sys::CUstreamBatchMemOpType as Kind;
let mut raw = sys::CUstreamBatchMemOpParams::default();
match self {
Self::Wait32 {
address,
value,
condition,
flags,
} => {
check_address(address, 4)?;
raw.waitValue.operation = Kind::CU_STREAM_MEM_OP_WAIT_VALUE_32;
raw.waitValue.address = to_u64(address.addr(), "memory operation address")?;
raw.waitValue.__bindgen_anon_1.value = value;
raw.waitValue.flags = u32::from(condition) | flags.bits();
}
Self::Wait64 {
address,
value,
condition,
flags,
} => {
check_address(address, 8)?;
raw.waitValue.operation = Kind::CU_STREAM_MEM_OP_WAIT_VALUE_64;
raw.waitValue.address = to_u64(address.addr(), "memory operation address")?;
raw.waitValue.__bindgen_anon_1.value64 = value;
raw.waitValue.flags = u32::from(condition) | flags.bits();
}
Self::Write32 { address, value } => {
check_address(address, 4)?;
raw.writeValue.operation = Kind::CU_STREAM_MEM_OP_WRITE_VALUE_32;
raw.writeValue.address = to_u64(address.addr(), "memory operation address")?;
raw.writeValue.__bindgen_anon_1.value = value;
}
Self::Write64 { address, value } => {
check_address(address, 8)?;
raw.writeValue.operation = Kind::CU_STREAM_MEM_OP_WRITE_VALUE_64;
raw.writeValue.address = to_u64(address.addr(), "memory operation address")?;
raw.writeValue.__bindgen_anon_1.value64 = value;
}
Self::Barrier(scope) => {
raw.memoryBarrier.operation = Kind::CU_STREAM_MEM_OP_BARRIER;
raw.memoryBarrier.flags = match scope {
MemoryBarrierScope::System => {
sys::CUstreamMemoryBarrier_flags::CU_STREAM_MEMORY_BARRIER_TYPE_SYS.0
}
MemoryBarrierScope::Device => {
sys::CUstreamMemoryBarrier_flags::CU_STREAM_MEMORY_BARRIER_TYPE_GPU.0
}
};
}
Self::FlushRemoteWrites => {
raw.flushRemoteWrites.operation = Kind::CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES;
}
}
Ok(raw)
}
}
pub(crate) fn native_batch(
operations: &[MemoryOperation],
) -> Result<Vec<sys::CUstreamBatchMemOpParams>> {
if operations.len() >= 256 {
return Err(Error::out_of_range("stream memory operation count"));
}
operations
.iter()
.copied()
.map(MemoryOperation::native)
.collect()
}
impl Stream {
pub unsafe fn memory_operations(&self, operations: &[MemoryOperation]) -> Result<()> {
let mut native = native_batch(operations)?;
unsafe { self.enqueue_memory_operations(&mut native) }
}
unsafe fn enqueue_memory_operations(
&self,
native: &mut [sys::CUstreamBatchMemOpParams],
) -> Result<()> {
if native.is_empty() {
return Ok(());
}
self.context().bind()?;
unsafe {
try_ffi!(sys::cuStreamBatchMemOp_v2(
self.as_raw(),
to_u32(native.len(), "stream memory operation count")?,
native.as_mut_ptr(),
0
))
}
}
}
macro_rules! word_operations {
($wait:ident, $write:ident, $word:ty, $native_wait:ident, $native_write:ident) => {
impl Stream {
pub unsafe fn $wait(
&self,
address: DevicePtr,
value: $word,
condition: WaitCondition,
flags: WaitFlags,
) -> Result<()> {
check_address(address, size_of::<$word>())?;
self.context().bind()?;
unsafe {
try_ffi!(sys::$native_wait(
self.as_raw(),
to_u64(address.addr(), "memory operation address")?,
value,
u32::from(condition) | flags.bits()
))
}
}
pub unsafe fn $write(&self, address: DevicePtr, value: $word) -> Result<()> {
check_address(address, size_of::<$word>())?;
self.context().bind()?;
unsafe {
try_ffi!(sys::$native_write(
self.as_raw(),
to_u64(address.addr(), "memory operation address")?,
value,
0
))
}
}
}
};
}
word_operations!(
wait_value32,
write_value32,
u32,
cuStreamWaitValue32_v2,
cuStreamWriteValue32_v2
);
word_operations!(
wait_value64,
write_value64,
u64,
cuStreamWaitValue64_v2,
cuStreamWriteValue64_v2
);
pub struct MemoryOperations {
operations: Vec<sys::CUstreamBatchMemOpParams>,
resources: Resources,
}
impl fmt::Debug for MemoryOperations {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemoryOperations")
.field("operation_count", &self.operations.len())
.field("resources", &self.resources)
.finish()
}
}
impl MemoryOperations {
pub unsafe fn create(operations: &[MemoryOperation], resources: Resources) -> Result<Self> {
Ok(Self {
operations: native_batch(operations)?,
resources,
})
}
}
unsafe impl Operation for MemoryOperations {
type Pending = ();
type Output = ();
fn enqueue(mut self, execution: &mut Execution) -> Result<()> {
unsafe {
execution.enqueue(self.resources, |stream| {
stream.enqueue_memory_operations(&mut self.operations)
})
}
}
unsafe fn resolve(pending: ()) -> Result<()> {
Ok(pending)
}
}
unsafe impl DeviceOperation for MemoryOperations {}
unsafe impl Recordable for MemoryOperations {
type Output = ();
fn record(mut self, recording: &mut Recording) -> Result<()> {
unsafe {
recording.enqueue(self.resources, |stream| {
stream.enqueue_memory_operations(&mut self.operations)
})
}
}
}