Skip to main content

sloth256_189/opencl/
mod.rs

1//! Universal OpenCL GPU implementation, supports cards both AMD, Nvidia and Intel.
2//!
3//! It supports all major GPU vendors, including support for multiple GPU, including support for
4//! multiple GPU vendors on the same machine at the same time.
5//!
6//! ### Linux support
7//! In all cases for OpenCL support to build (not needed in runtime), OpenCL header files and
8//! library are necessary, can be installed on Ubuntu as follows:
9//! ```bash
10//! sudo apt-get install ocl-icd-opencl-dev
11//! ```
12//!
13//! #### AMD
14//! Mesa OpenCL support is not compatible for AMD GPUs, you need to install ROCm-based OpenCL ICD.
15//!
16//! This can be done by downloading downloading and installing AMD driver installer from
17//! <https://www.amd.com/en/support>, installing will look something like this:
18//! ```bash
19//! sudo dpkg -i amdgpu-install_21.50.2.50002-1_all.deb
20//! ```
21//! After which you should have `amdgpu-install` command, use it to install OpenCL ICD as follows:
22//! ```bash
23//! sudo amdgpu-install --no-dkms --usecase=opencl
24//! ```
25//!
26//! ^ will only install OpenCL ICD and will keep Open Source kernel graphics driver as it was.
27//!
28//! Removal of all of the above is possible with:
29//! ```bash
30//! sudo amdgpu-install --uninstall
31//! sudo apt-get purge amdgpu-install
32//! ```
33//!
34//! #### Nvidia
35//! Proprietary driver with CUDA toolchain is needed, Open Source drivers are not supported.
36//!
37//! #### Intel
38//! Thankfully, for Intel GPU Open Source ICD works great:
39//! ```bash
40//! sudo apt-get install intel-opencl-icd
41//! ```
42
43// Including for linking purposes
44#[allow(unused_imports)]
45use openmp_sys;
46
47use std::borrow::Cow;
48use std::mem;
49use std::os::raw::c_char;
50use thiserror::Error;
51
52const ENCODE_CL: &str = concat!(include_str!("encode.cl"), "\0");
53const NVIDIA_SPECIFIC_CL: &str = concat!(include_str!("nvidia_specific.cl"), "\0");
54const MOD256_189_CU: &str = concat!(include_str!("mod256-189.cu"), "\0");
55const NON_NVIDIA_CL: &str = concat!(include_str!("non_nvidia.cl"), "\0");
56
57/// OpenCL encoding errors
58#[derive(Debug, Error)]
59pub enum OpenCLEncodeError {
60    /// Pieces argument is invalid, must be multiple of 4096-bytes pieces
61    #[error("Pieces argument is invalid, must be multiple of 4096-bytes pieces, {0} bytes given")]
62    InvalidPieces(usize),
63    /// IVs argument is invalid, must be multiple of 32-bytes IVs
64    #[error("IVs argument is invalid, must be multiple of 32-bytes pieces, {0} bytes given")]
65    InvalidIVs(usize),
66    /// Number of pieces should be the same as number of IVs
67    #[error("Number of pieces should be the same as number of IVs, {0} pieces and {1} IVs given")]
68    InvalidPiecesIVs(usize, usize),
69    /// OpenCL API returned an error code
70    #[error("OpenCL API error: {0}")]
71    OpenCLError(Cow<'static, str>),
72    /// OpenCL could not find any compatible device on the specified platform
73    /// 2026 = No devices, 2027 = No Nvidia GPUs, 2028 = No AMD GPUs, 2029 = No Intel GPUs,
74    /// 2035 = Pinned memory couldn't be allocated because no Nvidia GPU was found on the system
75    /// 2036 = There was no previously allocated pinned memory
76    #[error("No OpenCL compatible device could be found")]
77    OpenCLDeviceNotFound(i32),
78}
79
80impl OpenCLEncodeError {
81    /// Returns `Ok` in case code is not an error
82    fn from_return_code(return_code: i32) -> Result<(), Self> {
83        let error_string = match return_code {
84            0 => {
85                // No error
86                return Ok(());
87            }
88
89            // runtime errors
90            -1 => "CL_DEVICE_NOT_FOUND".into(),
91            -2 => "CL_DEVICE_NOT_AVAILABLE".into(),
92            -3 => "CL_COMPILER_NOT_AVAILABLE".into(),
93            -4 => "CL_MEM_OBJECT_ALLOCATION_FAILURE".into(),
94            -5 => "CL_OUT_OF_RESOURCES".into(),
95            -6 => "CL_OUT_OF_HOST_MEMORY".into(),
96            -7 => "CL_PROFILING_INFO_NOT_AVAILABLE".into(),
97            -8 => "CL_MEM_COPY_OVERLAP".into(),
98            -9 => "CL_IMAGE_FORMAT_MISMATCH".into(),
99            -10 => "CL_IMAGE_FORMAT_NOT_SUPPORTED".into(),
100            -11 => "CL_BUILD_PROGRAM_FAILURE".into(),
101            -12 => "CL_MAP_FAILURE".into(),
102            -13 => "CL_MISALIGNED_SUB_BUFFER_OFFSET".into(),
103            -14 => "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST ".into(),
104            -15 => "CL_COMPILE_PROGRAM_FAILURE".into(),
105            -16 => "CL_LINKER_NOT_AVAILABLE".into(),
106            -17 => "CL_LINK_PROGRAM_FAILURE".into(),
107            -18 => "CL_DEVICE_PARTITION_FAILED".into(),
108            -19 => "CL_KERNEL_ARG_INFO_NOT_AVAILABLE".into(),
109
110            // compile time errors
111            -30 => "CL_INVALID_VALUE".into(),
112            -31 => "CL_INVALID_DEVICE_TYPE".into(),
113            -32 => "CL_INVALID_PLATFORM".into(),
114            -33 => "CL_INVALID_DEVICE".into(),
115            -34 => "CL_INVALID_CONTEXT".into(),
116            -35 => "CL_INVALID_QUEUE_PROPERTIES".into(),
117            -36 => "CL_INVALID_COMMAND_QUEUE".into(),
118            -37 => "CL_INVALID_HOST_PTR".into(),
119            -38 => "CL_INVALID_MEM_OBJECT".into(),
120            -39 => "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR".into(),
121            -40 => "CL_INVALID_IMAGE_SIZE".into(),
122            -41 => "CL_INVALID_SAMPLER".into(),
123            -42 => "CL_INVALID_BINARY".into(),
124            -43 => "CL_INVALID_BUILD_OPTIONS".into(),
125            -44 => "CL_INVALID_PROGRAM".into(),
126            -45 => "CL_INVALID_PROGRAM_EXECUTABLE".into(),
127            -46 => "CL_INVALID_KERNEL_NAME".into(),
128            -47 => "CL_INVALID_KERNEL_DEFINITION".into(),
129            -48 => "CL_INVALID_KERNEL".into(),
130            -49 => "CL_INVALID_ARG_INDEX".into(),
131            -50 => "CL_INVALID_ARG_VALUE".into(),
132            -51 => "CL_INVALID_ARG_SIZE".into(),
133            -52 => "CL_INVALID_KERNEL_ARGS".into(),
134            -53 => "CL_INVALID_WORK_DIMENSION".into(),
135            -54 => "CL_INVALID_WORK_GROUP_SIZE".into(),
136            -55 => "CL_INVALID_WORK_ITEM_SIZE".into(),
137            -56 => "CL_INVALID_GLOBAL_OFFSET".into(),
138            -57 => "CL_INVALID_EVENT_WAIT_LIST".into(),
139            -58 => "CL_INVALID_EVENT".into(),
140            -59 => "CL_INVALID_OPERATION".into(),
141            -60 => "CL_INVALID_GL_OBJECT".into(),
142            -61 => "CL_INVALID_BUFFER_SIZE".into(),
143            -62 => "CL_INVALID_MIP_LEVEL".into(),
144            -63 => "CL_INVALID_GLOBAL_WORK_SIZE".into(),
145            -64 => "CL_INVALID_PROPERTY".into(),
146            -65 => "CL_INVALID_IMAGE_DESCRIPTOR".into(),
147            -66 => "CL_INVALID_COMPILER_OPTIONS".into(),
148            -67 => "CL_INVALID_LINKER_OPTIONS".into(),
149            -68 => "CL_INVALID_DEVICE_PARTITION_COUNT".into(),
150
151            // sloth256-189 encoding-specific errors
152            2026 => "SLOTH_NO_OPENCL_COMPATIBLE_GPUS".into(),
153            2027 => "SLOTH_NO_OPENCL_COMPATIBLE_NVIDIA_GPUS".into(),
154            2028 => "SLOTH_NO_OPENCL_COMPATIBLE_AMD_GPUS".into(),
155            2029 => "SLOTH_NO_OPENCL_COMPATIBLE_INTEL_GPUS".into(),
156
157            // Should never happen since the caller Rust
158            // function makes sure that there are more than 1024 pieces
159            2031 => "SLOTH_PIECES_NOT_MULTIPLE_OF_1024".into(),
160
161            // Pinned memory allocation fails if
162            // there's no OpenCL compatible Nvidia GPUs
163            2035 => "SLOTH_PINNED_MEMORY_ALLOCATION_FAILURE".into(),
164
165            // There was no pinned memory allocated previously
166            // so no memory to free
167            2036 => "SLOTH_NO_ALLOCATED_PINNED_MEMORY".into(),
168
169            // The work division between the CPU and the OpenCL compatible
170            // devices were not yet determined.
171            // Run the "determine_work_division_configuration" function before
172            // encoding.
173            2037 => "SLOTH_DEVICE_WORK_DIVISION_NOT_DETERMINED".into(),
174
175            code => format!("Unknown OpenCL error {}", code).into(),
176        };
177
178        Err(Self::OpenCLError(error_string))
179    }
180}
181
182// importing the functions from .c files
183mod ffi {
184    use std::os::raw::{c_char, c_int, c_uchar};
185
186    #[repr(C)]
187    pub(super) struct EncodeOpenCLInstances {
188        _data: [u8; 0],
189    }
190
191    extern "C" {
192        pub(super) fn sloth256_189_opencl_batch_encode(
193            inout: *mut c_uchar,
194            len: usize,
195            iv: *const c_uchar,
196            layers: usize,
197            instances: *const EncodeOpenCLInstances,
198        ) -> c_int;
199
200        pub(super) fn sloth256_189_opencl_init(
201            error: &mut c_int,
202            encode_cl: *const c_char,
203            nvidia_specific_cl: *const c_char,
204            mod256_189_cu: *const c_char,
205            non_nvidia_cl: *const c_char,
206        ) -> *const EncodeOpenCLInstances;
207
208        pub(super) fn sloth256_189_opencl_determine_factors(
209            size: usize,
210            layers: usize,
211            instances: *const EncodeOpenCLInstances,
212        ) -> c_int;
213
214        // Pinned memory allocation is not exposed due to low performance improvement (1-2%) and
215        // API complexity
216        // pub(super) fn sloth256_189_pinned_alloc_supported(
217        //     instances: *const EncodeOpenCLInstances,
218        // ) -> bool;
219        //
220        // pub(super) fn sloth256_189_pinned_alloc(
221        //     instances: *const EncodeOpenCLInstances,
222        //     size: usize,
223        //     error: &mut c_int,
224        // ) -> *mut u8;
225        //
226        // pub(super) fn sloth256_189_pinned_free(instances: *const EncodeOpenCLInstances) -> c_int;
227
228        pub(super) fn sloth256_189_opencl_cleanup(instances: *const EncodeOpenCLInstances)
229            -> c_int;
230    }
231}
232
233/// Batch to be encoded on GPU
234#[derive(Debug, Copy, Clone, Eq, PartialEq)]
235pub struct OpenClBatch {
236    /// Batch size (of pieces) in bytes (should be multiple of 4096)
237    pub size: usize,
238    /// Number of encoding layers
239    pub layers: usize,
240}
241
242/// OpenCL codec
243#[derive(Debug)]
244pub struct OpenClEncoder {
245    batch: Option<OpenClBatch>,
246    instances: *const ffi::EncodeOpenCLInstances,
247}
248
249// SAFETY: `EncodeOpenCLInstances` pointer is heap-allocated and will live as long as needed
250unsafe impl Send for OpenClEncoder {}
251
252impl OpenClEncoder {
253    /// Create new OpenCL codec instance for batch encoding on GPU.
254    ///
255    /// Batch information can be provided upfront to determine load distribution and do necessary
256    /// memory allocation.
257    pub fn new(batch: Option<OpenClBatch>) -> Result<Self, OpenCLEncodeError> {
258        if let Some(batch) = &batch {
259            // Ensure that the given size is valid
260            if batch.size % 4096 != 0 {
261                return Err(OpenCLEncodeError::InvalidPieces(batch.size));
262            }
263        }
264
265        let mut return_code: i32 = 0;
266        let instances = unsafe {
267            ffi::sloth256_189_opencl_init(
268                &mut return_code,
269                ENCODE_CL.as_ptr() as *const c_char,
270                NVIDIA_SPECIFIC_CL.as_ptr() as *const c_char,
271                MOD256_189_CU.as_ptr() as *const c_char,
272                NON_NVIDIA_CL.as_ptr() as *const c_char,
273            )
274        };
275
276        OpenCLEncodeError::from_return_code(return_code)?;
277
278        let mut encoder = Self {
279            batch: None,
280            instances,
281        };
282
283        if let Some(batch) = batch {
284            encoder.recalculate_work_division_configuration(batch)?;
285
286            encoder.batch.replace(batch);
287        }
288
289        Ok(encoder)
290    }
291
292    /// Sequentially encodes a batch of pieces using OpenCL.
293    ///
294    /// NOTE: This encode function works on batches of pieces and IVs.
295    ///
296    /// For smaller batches or encoding of individual pieces use CPU implementation.
297    pub fn encode(
298        &mut self,
299        pieces: &mut [u8],
300        ivs: &[u8],
301        layers: usize,
302    ) -> Result<(), OpenCLEncodeError> {
303        if pieces.len() % 4096 != 0 {
304            return Err(OpenCLEncodeError::InvalidPieces(pieces.len()));
305        }
306
307        if ivs.len() % 32 != 0 {
308            return Err(OpenCLEncodeError::InvalidIVs(ivs.len()));
309        }
310
311        if pieces.len() / 4096 != ivs.len() / 32 {
312            return Err(OpenCLEncodeError::InvalidPiecesIVs(
313                pieces.len() / 4096,
314                ivs.len() / 32,
315            ));
316        }
317
318        let batch = OpenClBatch {
319            size: pieces.len(),
320            layers,
321        };
322
323        if self.batch != Some(batch) {
324            self.recalculate_work_division_configuration(batch)?;
325
326            self.batch.replace(batch);
327        }
328
329        let return_code = unsafe {
330            ffi::sloth256_189_opencl_batch_encode(
331                pieces.as_mut_ptr(),
332                pieces.len(),
333                ivs.as_ptr(),
334                layers,
335                self.instances,
336            )
337        };
338
339        OpenCLEncodeError::from_return_code(return_code)
340    }
341
342    /// Cleans up the resources allocated in the initialization of the encode kernel.
343    ///
344    /// Prefer this over `drop()` because `drop()` will panic in case of error.
345    ///
346    /// NOTE: In case error is returned, memory used for kernel initialization might be leaked.
347    pub fn destroy(self) -> Result<(), OpenCLEncodeError> {
348        let return_code = unsafe { ffi::sloth256_189_opencl_cleanup(self.instances) };
349
350        // We don't want to run `Drop::drop` after this
351        mem::forget(self);
352
353        OpenCLEncodeError::from_return_code(return_code)
354    }
355
356    /// Determine the work division configuration between the CPU and the OpenCL compatible
357    /// devices for a given size and number of layers.
358    ///
359    /// Call this function after initialization and if the encoding size or number of layers
360    /// change.
361    fn recalculate_work_division_configuration(
362        &mut self,
363        batch: OpenClBatch,
364    ) -> Result<(), OpenCLEncodeError> {
365        // Ensure that the given size is valid
366        if batch.size % 4096 != 0 {
367            return Err(OpenCLEncodeError::InvalidPieces(batch.size));
368        }
369
370        let return_code = unsafe {
371            ffi::sloth256_189_opencl_determine_factors(batch.size, batch.layers, self.instances)
372        };
373
374        OpenCLEncodeError::from_return_code(return_code)
375    }
376}
377
378impl Drop for OpenClEncoder {
379    fn drop(&mut self) {
380        let return_code = unsafe { ffi::sloth256_189_opencl_cleanup(self.instances) };
381
382        OpenCLEncodeError::from_return_code(return_code).unwrap();
383    }
384}