mod config;
mod function;
mod image;
mod parameters;
pub mod artifact;
use std::{ffi::CString, ptr, result::Result as StdResult, sync::Arc};
use singe_core::report_cleanup_failure;
use singe_cuda_sys::driver;
use crate::{
context::Context,
error::{Error, Result},
library::Library,
module::artifact::ArtifactMetadata,
try_ffi,
types::DeviceFunction,
utility::to_usize,
};
pub use self::{
config::{LaunchAttribute, LaunchConfig, LaunchGeometry},
function::{
FunctionAttributes, KernelFunction, OccupancyFlags, OccupancyMaxPotentialBlockSize,
},
image::ModuleImage,
parameters::{EncodedKernelArgs, KernelLaunchArgs, KernelParameters, PushKernelArg},
};
#[derive(Debug)]
pub struct RawModule {
pub handle: driver::CUmodule,
pub context: Arc<Context>,
}
#[derive(Debug, Clone)]
pub struct Module {
inner: Arc<ModuleInner>,
}
#[derive(Debug)]
struct ModuleInner {
handle: driver::CUmodule,
context: Arc<Context>,
ownership: ModuleOwnership,
artifact_metadata: Option<Arc<ArtifactMetadata>>,
}
#[derive(Debug)]
enum ModuleOwnership {
Owned,
External,
Library { owner: Library },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum CodeOwnerId {
Module(usize),
Library(usize),
}
#[derive(Debug, Clone, Copy)]
pub struct Global<'a> {
ptr: *mut (),
size: usize,
_module: &'a Module,
}
#[derive(Debug, Clone, Copy)]
pub struct TextureReference<'a> {
handle: driver::CUtexref,
_module: &'a Module,
}
#[derive(Debug, Clone, Copy)]
pub struct SurfaceReference<'a> {
handle: driver::CUsurfref,
_module: &'a Module,
}
impl Module {
pub unsafe fn from_raw(raw: RawModule) -> Result<Self> {
unsafe { Self::from_raw_with_metadata(raw.handle, raw.context, None) }
}
pub(crate) unsafe fn from_raw_with_metadata(
handle: driver::CUmodule,
context: Arc<Context>,
artifact_metadata: Option<Arc<ArtifactMetadata>>,
) -> Result<Self> {
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(Self {
inner: Arc::new(ModuleInner {
handle,
context,
ownership: ModuleOwnership::Owned,
artifact_metadata,
}),
})
}
pub unsafe fn from_borrowed_raw(handle: driver::CUmodule, context: Arc<Context>) -> Self {
Self {
inner: Arc::new(ModuleInner {
handle,
context,
ownership: ModuleOwnership::External,
artifact_metadata: None,
}),
}
}
pub fn function(&self, name: &str) -> Result<KernelFunction> {
self.inner.context.bind()?;
let c_name = CString::new(name)?;
let mut handle = ptr::null_mut();
unsafe {
try_ffi!(driver::cuModuleGetFunction(
&raw mut handle,
self.inner.handle,
c_name.as_ptr()
))?;
}
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(KernelFunction {
handle: unsafe { DeviceFunction::from_raw(handle) },
module: self.clone(),
})
}
pub fn function_count(&self) -> Result<usize> {
self.inner.context.bind()?;
let mut count = 0;
unsafe {
try_ffi!(driver::cuModuleGetFunctionCount(
&raw mut count,
self.inner.handle
))?;
}
to_usize(count, "module function count")
}
#[must_use]
pub fn as_raw(&self) -> driver::CUmodule {
self.inner.handle
}
pub fn into_raw(self) -> StdResult<RawModule, Self> {
if !matches!(self.inner.ownership, ModuleOwnership::Owned) {
return Err(self);
}
match Arc::try_unwrap(self.inner) {
Ok(mut inner) => {
inner.ownership = ModuleOwnership::External;
Ok(RawModule {
handle: inner.handle,
context: Arc::clone(&inner.context),
})
}
Err(inner) => Err(Self { inner }),
}
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.inner.context
}
pub(crate) fn code_owner_id(&self) -> CodeOwnerId {
match &self.inner.ownership {
ModuleOwnership::Library { owner } => CodeOwnerId::Library(owner.code_owner_id()),
ModuleOwnership::Owned | ModuleOwnership::External => {
CodeOwnerId::Module(Arc::as_ptr(&self.inner).addr())
}
}
}
pub(crate) fn from_library(
handle: driver::CUmodule,
context: Arc<Context>,
library: Library,
) -> Self {
Self {
inner: Arc::new(ModuleInner {
handle,
context,
ownership: ModuleOwnership::Library { owner: library },
artifact_metadata: None,
}),
}
}
pub fn global(&self, name: &str) -> Result<Global<'_>> {
let c_name = CString::new(name)?;
let mut ptr = 0;
let mut size = 0;
self.inner.context.bind()?;
unsafe {
try_ffi!(driver::cuModuleGetGlobal_v2(
&raw mut ptr,
&raw mut size,
self.inner.handle,
c_name.as_ptr(),
))?;
}
Ok(Global {
ptr: ptr as _,
size: to_usize(size, "global byte count")?,
_module: self,
})
}
}
impl Drop for ModuleInner {
fn drop(&mut self) {
if !matches!(self.ownership, ModuleOwnership::Owned) {
return;
}
if let Err(error) = self.context.bind() {
report_cleanup_failure("bind the cuda context to unload", "cuda module", &error);
return;
}
unsafe {
if let Err(error) = try_ffi!(driver::cuModuleUnload(self.handle)) {
report_cleanup_failure("unload", "cuda module", &error);
}
}
}
}
unsafe impl Send for ModuleInner {}
unsafe impl Sync for ModuleInner {}
impl Global<'_> {
#[must_use]
pub const fn as_ptr(&self) -> *mut () {
self.ptr
}
#[must_use]
pub const fn byte_len(&self) -> usize {
self.size
}
}
impl TextureReference<'_> {
#[must_use]
pub const fn as_raw(&self) -> driver::CUtexref {
self.handle
}
}
impl SurfaceReference<'_> {
#[must_use]
pub const fn as_raw(&self) -> driver::CUsurfref {
self.handle
}
}