From 15c0de6de8cd51125588e2189a32d321cc081ca1 Mon Sep 17 00:00:00 2001 From: Michael Shaw Date: Tue, 11 Feb 2025 21:34:08 -0500 Subject: [PATCH] lock: add mutex Signed-off-by: Michael Shaw --- include/kernel/lock.h | 4 ++++ lib/lock.c | 20 +++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/include/kernel/lock.h b/include/kernel/lock.h index f9d848a..e97b593 100644 --- a/include/kernel/lock.h +++ b/include/kernel/lock.h @@ -3,9 +3,13 @@ #define _LOCK_H_ typedef int spinlock_t; +typedef spinlock_t mtx_t; int atomic_cmpxchg(volatile int *ptr, int cmpval, int newval); void spinlock_acquire(spinlock_t *lock); void spinlock_release(spinlock_t *lock); +void mtx_acquire(mtx_t *mtx); +void mtx_release(mtx_t *mtx); + #endif /* _LOCK_H_ */ diff --git a/lib/lock.c b/lib/lock.c index 63a7c81..0aff9fe 100644 --- a/lib/lock.c +++ b/lib/lock.c @@ -1,9 +1,16 @@ #include #include +#include + +static uint64_t spinlock_attempt_acquire(spinlock_t *lock) +{ + return atomic_cmpxchg(lock, 0, 1); +} + void spinlock_acquire(spinlock_t *lock) { - while (atomic_cmpxchg(lock, 0, 1)) + while (spinlock_attempt_acquire(lock)) ; } @@ -11,3 +18,14 @@ void spinlock_release(spinlock_t *lock) { atomic_cmpxchg(lock, 1, 0); } + +void mtx_acquire(mtx_t *mtx) +{ + while (spinlock_attempt_acquire(mtx)) + sswtch(); +} + +void mtx_release(mtx_t *mtx) +{ + spinlock_release(mtx); +}