arceos_posix_api/imp/pthread/
mutex.rs

1use crate::{ctypes, utils::check_null_mut_ptr};
2
3use axerrno::LinuxResult;
4use axsync::Mutex;
5
6use core::ffi::c_int;
7use core::mem::{ManuallyDrop, align_of, size_of};
8
9static_assertions::const_assert_eq!(
10    size_of::<ctypes::pthread_mutex_t>(),
11    size_of::<PthreadMutex>()
12);
13static_assertions::const_assert_eq!(
14    align_of::<ctypes::pthread_mutex_t>(),
15    align_of::<PthreadMutex>()
16);
17
18#[repr(C)]
19pub struct PthreadMutex(Mutex<()>);
20
21impl PthreadMutex {
22    const fn new() -> Self {
23        Self(Mutex::new(()))
24    }
25
26    fn lock(&self) -> LinuxResult {
27        let _guard = ManuallyDrop::new(self.0.lock());
28        Ok(())
29    }
30
31    fn unlock(&self) -> LinuxResult {
32        unsafe { self.0.force_unlock() };
33        Ok(())
34    }
35}
36
37/// Initialize a mutex.
38pub fn sys_pthread_mutex_init(
39    mutex: *mut ctypes::pthread_mutex_t,
40    _attr: *const ctypes::pthread_mutexattr_t,
41) -> c_int {
42    debug!("sys_pthread_mutex_init <= {:#x}", mutex as usize);
43    syscall_body!(sys_pthread_mutex_init, {
44        check_null_mut_ptr(mutex)?;
45        unsafe {
46            mutex.cast::<PthreadMutex>().write(PthreadMutex::new());
47        }
48        Ok(0)
49    })
50}
51
52/// Lock the given mutex.
53pub fn sys_pthread_mutex_lock(mutex: *mut ctypes::pthread_mutex_t) -> c_int {
54    debug!("sys_pthread_mutex_lock <= {:#x}", mutex as usize);
55    syscall_body!(sys_pthread_mutex_lock, {
56        check_null_mut_ptr(mutex)?;
57        unsafe {
58            (*mutex.cast::<PthreadMutex>()).lock()?;
59        }
60        Ok(0)
61    })
62}
63
64/// Unlock the given mutex.
65pub fn sys_pthread_mutex_unlock(mutex: *mut ctypes::pthread_mutex_t) -> c_int {
66    debug!("sys_pthread_mutex_unlock <= {:#x}", mutex as usize);
67    syscall_body!(sys_pthread_mutex_unlock, {
68        check_null_mut_ptr(mutex)?;
69        unsafe {
70            (*mutex.cast::<PthreadMutex>()).unlock()?;
71        }
72        Ok(0)
73    })
74}