use core::ffi::{c_char, c_int};
use core::marker::PhantomData;
use core::ptr::NonNull;
use core::slice;
use std::ffi::{CStr, CString};
use onemkl_sys as sys;
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Version {
pub major: i32,
pub minor: i32,
pub update: i32,
pub build: String,
pub processor: String,
pub platform: String,
}
pub fn version() -> Version {
let mut v = sys::MKLVersion::default();
unsafe { sys::MKL_Get_Version(&mut v) };
Version {
major: v.MajorVersion,
minor: v.MinorVersion,
update: v.UpdateVersion,
build: c_str_to_owned(v.Build),
processor: c_str_to_owned(v.Processor),
platform: c_str_to_owned(v.Platform),
}
}
pub fn version_string() -> String {
let mut buf = vec![0u8; 256];
unsafe {
sys::MKL_Get_Version_String(buf.as_mut_ptr().cast::<c_char>(), buf.len() as c_int);
}
if let Some(end) = buf.iter().position(|&b| b == 0) {
buf.truncate(end);
}
let trimmed: Vec<u8> = buf.into_iter().rev().skip_while(|&b| b == b' ').collect();
let mut out: Vec<u8> = trimmed.into_iter().rev().collect();
out.retain(|&b| b != 0);
String::from_utf8_lossy(&out).into_owned()
}
pub fn set_num_threads(n: i32) {
unsafe { sys::MKL_Set_Num_Threads(n) };
}
pub fn set_num_threads_local(n: i32) -> i32 {
unsafe { sys::MKL_Set_Num_Threads_Local(n) }
}
pub struct ThreadCountGuard {
previous: i32,
}
impl ThreadCountGuard {
pub fn new(n: i32) -> Self {
let previous = unsafe { sys::MKL_Set_Num_Threads_Local(n) };
Self { previous }
}
}
impl Drop for ThreadCountGuard {
fn drop(&mut self) {
unsafe { sys::MKL_Set_Num_Threads_Local(self.previous) };
}
}
pub fn max_threads() -> i32 {
unsafe { sys::MKL_Get_Max_Threads() }
}
pub fn set_dynamic(flag: bool) {
unsafe { sys::MKL_Set_Dynamic(if flag { 1 } else { 0 }) };
}
pub fn dynamic() -> bool {
unsafe { sys::MKL_Get_Dynamic() != 0 }
}
pub fn set_verbose(flag: bool) {
unsafe { sys::MKL_Verbose(if flag { 1 } else { 0 }) };
}
pub fn set_verbose_output_file(path: Option<&str>) -> Result<()> {
let status = match path {
Some(p) => {
let cstr = CString::new(p).map_err(|_| {
Error::InvalidArgument("verbose output path contains a NUL byte")
})?;
unsafe { sys::MKL_Verbose_Output_File(cstr.as_ptr()) }
}
None => unsafe { sys::MKL_Verbose_Output_File(core::ptr::null()) },
};
if status == 0 {
Ok(())
} else {
Err(Error::InvalidArgument(
"MKL_Verbose_Output_File failed (path inaccessible?)",
))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MemStat {
pub bytes_allocated: i64,
pub num_buffers: i32,
}
pub fn mem_stat() -> MemStat {
let mut nbuffers: c_int = 0;
let bytes = unsafe { sys::MKL_Mem_Stat(&mut nbuffers) };
MemStat {
bytes_allocated: bytes,
num_buffers: nbuffers,
}
}
pub fn peak_mem_usage(reset: bool) -> i64 {
let r: c_int = if reset { 1 } else { 0 };
unsafe { sys::MKL_Peak_Mem_Usage(r) }
}
pub fn free_buffers() {
unsafe { sys::MKL_Free_Buffers() };
}
pub fn thread_free_buffers() {
unsafe { sys::MKL_Thread_Free_Buffers() };
}
pub fn set_memory_limit(mem_type: i32, limit_bytes: usize) -> Result<()> {
let status = unsafe { sys::MKL_Set_Memory_Limit(mem_type, limit_bytes) };
if status == 0 {
Ok(())
} else {
Err(Error::InvalidArgument(
"MKL_Set_Memory_Limit rejected the requested limit",
))
}
}
pub struct AlignedBuffer<T> {
ptr: NonNull<T>,
len: usize,
_marker: PhantomData<T>,
}
unsafe impl<T: Send> Send for AlignedBuffer<T> {}
unsafe impl<T: Sync> Sync for AlignedBuffer<T> {}
impl<T> AlignedBuffer<T> {
pub fn new(len: usize, alignment: usize) -> Result<Self>
where
T: Default + Copy,
{
let mut buf = Self::new_uninit(len, alignment)?;
let default = T::default();
for slot in buf.as_mut_slice().iter_mut() {
*slot = default;
}
Ok(buf)
}
pub fn new_uninit(len: usize, alignment: usize) -> Result<Self> {
if !alignment.is_power_of_two() {
return Err(Error::InvalidArgument(
"alignment must be a power of two",
));
}
if alignment < core::mem::align_of::<T>() {
return Err(Error::InvalidArgument(
"alignment must be a multiple of align_of::<T>()",
));
}
let bytes = len.checked_mul(core::mem::size_of::<T>()).ok_or(
Error::InvalidArgument("len * size_of::<T>() overflowed"),
)?;
let ptr = unsafe { sys::MKL_malloc(bytes, alignment as c_int) };
if ptr.is_null() {
return Err(Error::AllocationFailure);
}
let ptr = unsafe { NonNull::new_unchecked(ptr.cast::<T>()) };
Ok(Self {
ptr,
len,
_marker: PhantomData,
})
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.len
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
#[must_use]
pub fn as_slice(&self) -> &[T] {
unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
}
#[inline]
#[must_use]
pub fn as_mut_slice(&mut self) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
}
#[inline]
#[must_use]
pub fn as_ptr(&self) -> *const T {
self.ptr.as_ptr()
}
#[inline]
#[must_use]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.ptr.as_ptr()
}
}
impl<T> Drop for AlignedBuffer<T> {
fn drop(&mut self) {
unsafe { sys::MKL_free(self.ptr.as_ptr().cast()) };
}
}
impl<T> core::ops::Deref for AlignedBuffer<T> {
type Target = [T];
#[inline]
fn deref(&self) -> &[T] {
self.as_slice()
}
}
impl<T> core::ops::DerefMut for AlignedBuffer<T> {
#[inline]
fn deref_mut(&mut self) -> &mut [T] {
self.as_mut_slice()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IsaLevel {
Sse42,
Avx2,
Avx2E1,
Avx512,
Avx512E1,
Avx512E2,
Avx512E3,
Avx512E4,
Avx512E5,
Avx10,
}
impl IsaLevel {
#[inline]
fn as_int(self) -> c_int {
let v = match self {
Self::Sse42 => sys::MKL_ENABLE_SSE4_2,
Self::Avx2 => sys::MKL_ENABLE_AVX2,
Self::Avx2E1 => sys::MKL_ENABLE_AVX2_E1,
Self::Avx512 => sys::MKL_ENABLE_AVX512,
Self::Avx512E1 => sys::MKL_ENABLE_AVX512_E1,
Self::Avx512E2 => sys::MKL_ENABLE_AVX512_E2,
Self::Avx512E3 => sys::MKL_ENABLE_AVX512_E3,
Self::Avx512E4 => sys::MKL_ENABLE_AVX512_E4,
Self::Avx512E5 => sys::MKL_ENABLE_AVX512_E5,
Self::Avx10 => sys::MKL_ENABLE_AVX10,
};
v as c_int
}
}
pub fn enable_instructions(level: IsaLevel) -> Result<()> {
let r = unsafe { sys::MKL_Enable_Instructions(level.as_int()) };
if r == 1 {
Ok(())
} else {
Err(Error::InvalidArgument(
"MKL_Enable_Instructions: CPU does not support the requested ISA level",
))
}
}
pub fn cpu_clocks() -> u64 {
let mut clocks: u64 = 0;
unsafe { sys::MKL_Get_Cpu_Clocks(&mut clocks) };
clocks
}
pub fn cpu_frequency_ghz() -> f64 {
unsafe { sys::MKL_Get_Cpu_Frequency() }
}
pub fn max_cpu_frequency_ghz() -> f64 {
unsafe { sys::MKL_Get_Max_Cpu_Frequency() }
}
pub fn finalize() {
unsafe { sys::MKL_Finalize() };
}
#[inline]
fn c_str_to_owned(p: *const c_char) -> String {
if p.is_null() {
return String::new();
}
unsafe { CStr::from_ptr(p) }
.to_string_lossy()
.into_owned()
}