fix dependency check logic cause config always disabled
[lunaix-os.git] / lunaix-os / kernel / ds / mutex.c
index fd14df5042800aa55a4b14b15cecceed245bf1a3..4aac422191e5f3cc21721e18c59c7e9ba23c2642 100644 (file)
@@ -1,27 +1,56 @@
 #include <lunaix/ds/mutex.h>
 #include <lunaix/process.h>
-#include <lunaix/sched.h>
+#include <lunaix/kpreempt.h>
 
-void
-mutex_lock(mutex_t* mutex)
+#define __do_lock(mutext)               \
+    ({                                  \
+        atomic_fetch_add(&mutex->lk, 1);\
+        mutex->owner = __current->pid;  \
+    })
+
+static inline bool must_inline
+__mutex_check_owner(mutex_t* mutex)
 {
-    if (atomic_load(&mutex->lk) && mutex->owner == __current->pid) {
-        atomic_fetch_add(&mutex->lk, 1);
-        return;
-    }
+    return mutex->owner == __current->pid;
+}
 
+static inline void must_inline
+__mutext_lock(mutex_t* mutex)
+{
     while (atomic_load(&mutex->lk)) {
-        sched_pass();
+        preempt_current();
     }
 
-    atomic_fetch_add(&mutex->lk, 1);
-    mutex->owner = __current->pid;
+    __do_lock(mutex);
+}
+
+static inline void must_inline
+__mutext_unlock(mutex_t* mutex)
+{
+    if (__mutex_check_owner(mutex))
+        atomic_fetch_sub(&mutex->lk, 1);
+}
+
+void
+mutex_lock(mutex_t* mutex)
+{
+    __mutext_lock(mutex);
+}
+
+bool
+mutex_trylock(mutex_t* mutex)
+{
+    if (atomic_load(&mutex->lk))
+        return false;
+
+    __do_lock(mutex);
+    return true;
 }
 
 void
 mutex_unlock(mutex_t* mutex)
 {
-    mutex_unlock_for(mutex, __current->pid);
+    __mutext_unlock(mutex);
 }
 
 void
@@ -31,4 +60,21 @@ mutex_unlock_for(mutex_t* mutex, pid_t pid)
         return;
     }
     atomic_fetch_sub(&mutex->lk, 1);
+}
+
+void
+mutex_lock_nested(mutex_t* mutex)
+{
+    if (atomic_load(&mutex->lk) && __mutex_check_owner(mutex)) {
+        atomic_fetch_add(&mutex->lk, 1);
+        return;
+    }
+
+    __mutext_lock(mutex);
+}
+
+void
+mutex_unlock_nested(mutex_t* mutex)
+{
+    mutex_unlock_for(mutex, __current->pid);
 }
\ No newline at end of file