Fix file system racing and ext2 directory insertion (#58)
[lunaix-os.git] / lunaix-os / includes / lunaix / ds / spinlock.h
1 #ifndef __LUNAIX_SPIN_H
2 #define __LUNAIX_SPIN_H
3
4 #include <lunaix/types.h>
5
6 struct spinlock
7 {
8     volatile bool flag;
9 };
10
11 #define DEFINE_SPINLOCK(name)   \
12     struct spinlock name = { .flag = false }
13
14 typedef struct spinlock spinlock_t;
15
16 /*
17     TODO we might use our own construct for atomic ops
18          But we will do itlater, currently this whole 
19          kernel is on a single long thread of fate, 
20          there won't be any hardware concurrent access 
21          happened here.
22 */
23
24 static inline void
25 spinlock_init(spinlock_t* lock)
26 {
27     lock->flag = false;
28 }
29
30 static inline bool spinlock_try_acquire(spinlock_t* lock)
31 {
32     if (lock->flag){
33         return false;
34     }
35
36     return (lock->flag = true);
37 }
38
39 static inline void spinlock_acquire(spinlock_t* lock)
40 {
41     while (lock->flag);
42     lock->flag = true;
43 }
44
45 static inline void spinlock_release(spinlock_t* lock)
46 {
47     lock->flag = false;
48 }
49
50 #define DEFINE_SPINLOCK_OPS(type, lock_accessor)                            \
51     static inline void lock(type obj) { spinlock_acquire(&obj->lock_accessor); }    \
52     static inline void unlock(type obj) { spinlock_release(&obj->lock_accessor); }    
53
54 #endif /* __LUNAIX_SPIN_H */