xref: /haiku/headers/private/kernel/lock.h (revision 81f5654c124bf46fba0fd251f208e2d88d81e1ce)
1 /*
2 ** Copyright 2001-2002, Travis Geiselbrecht. All rights reserved.
3 ** Distributed under the terms of the NewOS License.
4 */
5 #ifndef _KERNEL_LOCK_H
6 #define _KERNEL_LOCK_H
7 
8 
9 #include <OS.h>
10 #include <debug.h>
11 
12 
13 typedef struct recursive_lock {
14 	sem_id		sem;
15 	thread_id	holder;
16 	int			recursion;
17 } recursive_lock;
18 
19 #define ASSERT_LOCKED_RECURSIVE(r) { ASSERT(thread_get_current_thread_id() == (r)->holder); }
20 
21 typedef struct mutex {
22 	sem_id		sem;
23 	thread_id	holder;
24 } mutex;
25 
26 #define ASSERT_LOCKED_MUTEX(m) { ASSERT(thread_get_current_thread_id() == (m)->holder); }
27 
28 typedef struct benaphore {
29 	sem_id	sem;
30 	int32	count;
31 } benaphore;
32 
33 // Note: this is currently a trivial r/w lock implementation
34 //	it will be replaced with something better later - this
35 //	or a similar API will be made publically available at this point.
36 typedef struct rw_lock {
37 	sem_id		sem;
38 	int32		count;
39 	benaphore	writeLock;
40 } rw_lock;
41 
42 #define RW_MAX_READERS 1000000
43 
44 
45 #ifdef __cplusplus
46 extern "C" {
47 #endif
48 
49 extern status_t	recursive_lock_init(recursive_lock *lock, const char *name);
50 extern void recursive_lock_destroy(recursive_lock *lock);
51 extern bool recursive_lock_lock(recursive_lock *lock);
52 extern bool recursive_lock_unlock(recursive_lock *lock);
53 extern int	recursive_lock_get_recursion(recursive_lock *lock);
54 
55 extern status_t	mutex_init(mutex *m, const char *name);
56 extern void mutex_destroy(mutex *m);
57 extern void mutex_lock(mutex *m);
58 extern void mutex_unlock(mutex *m);
59 
60 extern status_t benaphore_init(benaphore *ben, const char *name);
61 extern void benaphore_destroy(benaphore *ben);
62 
63 static inline status_t
64 benaphore_lock_etc(benaphore *ben, uint32 flags, bigtime_t timeout)
65 {
66 	if (atomic_add(&ben->count, -1) <= 0)
67 		return acquire_sem_etc(ben->sem, 1, flags, timeout);
68 
69 	return B_OK;
70 }
71 
72 
73 static inline status_t
74 benaphore_lock(benaphore *ben)
75 {
76 	if (atomic_add(&ben->count, -1) <= 0)
77 		return acquire_sem(ben->sem);
78 
79 	return B_OK;
80 }
81 
82 
83 static inline status_t
84 benaphore_unlock(benaphore *ben)
85 {
86 	if (atomic_add(&ben->count, 1) < 0)
87 		return release_sem(ben->sem);
88 
89 	return B_OK;
90 }
91 
92 extern status_t rw_lock_init(rw_lock *lock, const char *name);
93 extern void rw_lock_destroy(rw_lock *lock);
94 extern status_t rw_lock_read_lock(rw_lock *lock);
95 extern status_t rw_lock_read_unlock(rw_lock *lock);
96 extern status_t rw_lock_write_lock(rw_lock *lock);
97 extern status_t rw_lock_write_unlock(rw_lock *lock);
98 
99 #ifdef __cplusplus
100 }
101 #endif
102 
103 #endif	/* _KERNEL_LOCK_H */
104