aboutsummaryrefslogtreecommitdiffhomepage
path: root/notcuda/src/impl/module.rs
blob: e19d8de3d1b799057220ef9a90f413bd8976df5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use std::{
    collections::hash_map, collections::HashMap, ffi::c_void, ffi::CStr, ffi::CString, mem,
    os::raw::c_char, ptr, slice,
};

use super::{
    device, function::Function, function::FunctionData, CUresult, GlobalState, HasLivenessCookie,
    LiveCheck,
};
use ptx;

pub type Module = LiveCheck<ModuleData>;

impl HasLivenessCookie for ModuleData {
    #[cfg(target_pointer_width = "64")]
    const COOKIE: usize = 0xf1313bd46505f98a;

    #[cfg(target_pointer_width = "32")]
    const COOKIE: usize = 0xbdbe3f15;

    const LIVENESS_FAIL: CUresult = CUresult::CUDA_ERROR_INVALID_HANDLE;

    fn try_drop(&mut self) -> Result<(), CUresult> {
        Ok(())
    }
}

pub struct ModuleData {
    pub spirv: SpirvModule,
    // This should be a Vec<>, but I'm feeling lazy
    pub device_binaries: HashMap<device::Index, CompiledModule>,
}

pub struct SpirvModule {
    pub binaries: Vec<u32>,
    pub kernel_info: HashMap<String, ptx::KernelInfo>,
    pub should_link_ptx_impl: Option<&'static [u8]>,
    pub build_options: CString,
}

pub struct CompiledModule {
    pub base: l0::Module,
    pub kernels: HashMap<CString, Box<Function>>,
}

impl<L, T, E> From<ptx::ParseError<L, T, E>> for CUresult {
    fn from(_: ptx::ParseError<L, T, E>) -> Self {
        CUresult::CUDA_ERROR_INVALID_PTX
    }
}

impl From<ptx::TranslateError> for CUresult {
    fn from(_: ptx::TranslateError) -> Self {
        CUresult::CUDA_ERROR_INVALID_PTX
    }
}

impl SpirvModule {
    pub fn new_raw<'a>(text: *const c_char) -> Result<Self, CUresult> {
        let u8_text = unsafe { CStr::from_ptr(text) };
        let ptx_text = u8_text
            .to_str()
            .map_err(|_| CUresult::CUDA_ERROR_INVALID_PTX)?;
        Self::new(ptx_text)
    }

    pub fn new<'a>(ptx_text: &str) -> Result<Self, CUresult> {
        let mut errors = Vec::new();
        let ast = ptx::ModuleParser::new().parse(&mut errors, ptx_text)?;
        let spirv_module = ptx::to_spirv_module(ast)?;
        Ok(SpirvModule {
            binaries: spirv_module.assemble(),
            kernel_info: spirv_module.kernel_info,
            should_link_ptx_impl: spirv_module.should_link_ptx_impl,
            build_options: spirv_module.build_options,
        })
    }

    pub fn compile(&self, ctx: &mut l0::Context, dev: &l0::Device) -> Result<l0::Module, CUresult> {
        let byte_il = unsafe {
            slice::from_raw_parts(
                self.binaries.as_ptr() as *const u8,
                self.binaries.len() * mem::size_of::<u32>(),
            )
        };
        let l0_module = l0::Module::build_spirv(ctx, dev, byte_il, None).0?;
        Ok(l0_module)
    }
}

pub fn get_function(
    hfunc: *mut *mut Function,
    hmod: *mut Module,
    name: *const c_char,
) -> Result<(), CUresult> {
    if hfunc == ptr::null_mut() || hmod == ptr::null_mut() || name == ptr::null() {
        return Err(CUresult::CUDA_ERROR_INVALID_VALUE);
    }
    let name = unsafe { CStr::from_ptr(name) }.to_owned();
    let function: *mut Function = GlobalState::lock_current_context(|ctx| {
        let module = unsafe { &mut *hmod }.as_result_mut()?;
        let device = unsafe { &mut *ctx.device };
        let compiled_module = match module.device_binaries.entry(device.index) {
            hash_map::Entry::Occupied(entry) => entry.into_mut(),
            hash_map::Entry::Vacant(entry) => {
                let new_module = CompiledModule {
                    base: module.spirv.compile(&mut device.l0_context, &device.base)?,
                    kernels: HashMap::new(),
                };
                entry.insert(new_module)
            }
        };
        let kernel = match compiled_module.kernels.entry(name) {
            hash_map::Entry::Occupied(entry) => entry.into_mut().as_mut(),
            hash_map::Entry::Vacant(entry) => {
                let kernel_info = module
                    .spirv
                    .kernel_info
                    .get(unsafe {
                        std::str::from_utf8_unchecked(entry.key().as_c_str().to_bytes())
                    })
                    .ok_or(CUresult::CUDA_ERROR_NOT_FOUND)?;
                let mut kernel =
                    l0::Kernel::new_resident(&compiled_module.base, entry.key().as_c_str())?;
                kernel.set_indirect_access(
                    l0::sys::ze_kernel_indirect_access_flags_t::ZE_KERNEL_INDIRECT_ACCESS_FLAG_DEVICE
                    | l0::sys::ze_kernel_indirect_access_flags_t::ZE_KERNEL_INDIRECT_ACCESS_FLAG_HOST
                    | l0::sys::ze_kernel_indirect_access_flags_t::ZE_KERNEL_INDIRECT_ACCESS_FLAG_SHARED
                )?;
                entry.insert(Box::new(Function::new(FunctionData {
                    base: kernel,
                    arg_size: kernel_info.arguments_sizes.clone(),
                    use_shared_mem: kernel_info.uses_shared_mem,
                })))
            }
        };
        Ok::<_, CUresult>(kernel as *mut _)
    })??;
    unsafe { *hfunc = function };
    Ok(())
}

pub(crate) fn load_data(pmod: *mut *mut Module, image: *const c_void) -> Result<(), CUresult> {
    let spirv_data = SpirvModule::new_raw(image as *const _)?;
    load_data_impl(pmod, spirv_data)
}

pub fn load_data_impl(pmod: *mut *mut Module, spirv_data: SpirvModule) -> Result<(), CUresult> {
    let module = GlobalState::lock_current_context(|ctx| {
        let device = unsafe { &mut *ctx.device };
        let l0_module = spirv_data.compile(&mut device.l0_context, &device.base)?;
        let mut device_binaries = HashMap::new();
        let compiled_module = CompiledModule {
            base: l0_module,
            kernels: HashMap::new(),
        };
        device_binaries.insert(device.index, compiled_module);
        let module_data = ModuleData {
            spirv: spirv_data,
            device_binaries,
        };
        Ok::<_, CUresult>(module_data)
    })??;
    let module_ptr = Box::into_raw(Box::new(Module::new(module)));
    unsafe { *pmod = module_ptr };
    Ok(())
}

pub(crate) fn unload(module: *mut Module) -> Result<(), CUresult> {
    if module == ptr::null_mut() {
        return Err(CUresult::CUDA_ERROR_INVALID_VALUE);
    }
    GlobalState::lock(|_| Module::destroy_impl(module))?
}