parlib: Add reader-writer sleeping locks
[akaros.git] / user / parlib / include / parlib / uthread.h
1 #pragma once
2
3 #include <parlib/vcore.h>
4 #include <parlib/signal.h>
5 #include <parlib/spinlock.h>
6 #include <parlib/parlib.h>
7 #include <parlib/kref.h>
8 #include <ros/syscall.h>
9 #include <sys/queue.h>
10 #include <time.h>
11
12 __BEGIN_DECLS
13
14 #define UTHREAD_DONT_MIGRATE            0x001 /* don't move to another vcore */
15 #define UTHREAD_SAVED                           0x002 /* uthread's state is in utf */
16 #define UTHREAD_FPSAVED                         0x004 /* uthread's FP state is in uth->as */
17 #define UTHREAD_IS_THREAD0                      0x008 /* thread0: glibc's main() thread */
18
19 /* Thread States */
20 #define UT_RUNNING              1
21 #define UT_NOT_RUNNING  2
22
23 /* Externally blocked thread reasons (for uthread_has_blocked()) */
24 #define UTH_EXT_BLK_MUTEX                       1
25 #define UTH_EXT_BLK_EVENTQ                      2
26 #define UTH_EXT_BLK_YIELD                       3
27 #define UTH_EXT_BLK_MISC                        4
28
29 /* One per joiner, usually kept on the stack. */
30 struct uth_join_kicker {
31         struct kref                                     kref;
32         struct uthread                          *joiner;
33 };
34
35 /* Join states, stored in the join_ctl */
36 #define UTH_JOIN_DETACHED               1
37 #define UTH_JOIN_JOINABLE               2
38 #define UTH_JOIN_HAS_JOINER             3
39 #define UTH_JOIN_EXITED                 4
40
41 /* One per uthread, to encapsulate all the join fields. */
42 struct uth_join_ctl {
43         atomic_t                                        state;
44         void                                            *retval;
45         void                                            **retval_loc;
46         struct uth_join_kicker          *kicker;
47 };
48
49 /* Bare necessities of a user thread.  2LSs should allocate a bigger struct and
50  * cast their threads to uthreads when talking with vcore code.  Vcore/default
51  * 2LS code won't touch udata or beyond. */
52 struct uthread {
53         struct user_context u_ctx;
54         struct ancillary_state as;
55         void *tls_desc;
56         int flags;
57         int state;
58         struct uth_join_ctl join_ctl;
59         struct sigstate sigstate;
60         int notif_disabled_depth;
61         TAILQ_ENTRY(uthread) sync_next;
62         struct syscall *sysc;   /* syscall we're blocking on, if any */
63         struct syscall local_sysc;      /* for when we don't want to use the stack */
64         void (*yield_func)(struct uthread*, void*);
65         void *yield_arg;
66         int err_no;
67         char err_str[MAX_ERRSTR_LEN];
68 };
69 TAILQ_HEAD(uth_tailq, uthread);
70
71 extern __thread struct uthread *current_uthread;
72
73
74 /* This struct is undefined.  We use it instead of void * so we can get
75  * compiler warnings if someone passes the wrong pointer type.  Internally, 2LSs
76  * and the default implementation use another object type. */
77 typedef struct __uth_sync_opaque * uth_sync_t;
78
79 /* 2LS-independent synchronization code (e.g. uthread mutexes) uses these
80  * helpers to access 2LS-specific functions.
81  *
82  * Note the spinlock associated with the higher-level sync primitive is held for
83  * these (where applicable). */
84 uth_sync_t __uth_sync_alloc(void);
85 void __uth_sync_free(uth_sync_t sync);
86 struct uthread *__uth_sync_get_next(uth_sync_t sync);
87 bool __uth_sync_get_uth(uth_sync_t sync, struct uthread *uth);
88 /* 2LSs that use default sync objs will call this in their has_blocked op. */
89 void __uth_default_sync_enqueue(struct uthread *uth, uth_sync_t sync);
90
91 /* 2L-Scheduler operations.  Examples in pthread.c. */
92 struct schedule_ops {
93         /**** These functions must be defined ****/
94         /* Functions supporting thread ops */
95         void (*sched_entry)(void);
96         void (*thread_runnable)(struct uthread *);
97         void (*thread_paused)(struct uthread *);
98         void (*thread_blockon_sysc)(struct uthread *, void *);
99         void (*thread_has_blocked)(struct uthread *, uth_sync_t, int);
100         void (*thread_refl_fault)(struct uthread *, struct user_context *);
101         void (*thread_exited)(struct uthread *);
102         struct uthread *(*thread_create)(void *(*)(void *), void *);
103         /**** Defining these functions is optional. ****/
104         uth_sync_t (*sync_alloc)(void);
105         void (*sync_free)(uth_sync_t);
106         struct uthread *(*sync_get_next)(uth_sync_t);
107         bool (*sync_get_uth)(uth_sync_t, struct uthread *);
108         /* Functions event handling wants */
109         void (*preempt_pending)(void);
110 };
111 extern struct schedule_ops *sched_ops;
112
113 /* Low-level _S code calls this for basic uthreading without a 2LS */
114 void uthread_lib_init(void);
115 /* Call this from your 2LS init routines.  Pass it a uthread representing
116  * thread0, your 2LS ops, and your syscall handler + data.
117  *
118  * When it returns, you're in _M mode (thread0 on vcore0) */
119 void uthread_2ls_init(struct uthread *uthread, struct schedule_ops *ops,
120                       void (*handle_sysc)(struct event_msg *, unsigned int,
121                                           void *),
122                       void *data);
123 /* Call this to become an mcp capable of worling with uthreads. */
124 void uthread_mcp_init(void);
125
126 /* Functions to make/manage uthreads.  Can be called by functions such as
127  * pthread_create(), which can wrap these with their own stuff (like attrs,
128  * retvals, etc). */
129
130 struct uth_thread_attr {
131         bool want_tls;          /* default, no */
132         bool detached;          /* default, no */
133 };
134
135 struct uth_join_request {
136         struct uthread                          *uth;
137         void                                            **retval_loc;
138 };
139
140 /* uthread_init() does the uthread initialization of a uthread that the caller
141  * created.  Call this whenever you are "starting over" with a thread.  Pass in
142  * attr, if you want to override any defaults. */
143 void uthread_init(struct uthread *new_thread, struct uth_thread_attr *attr);
144 /* uthread_create() is a front-end for getting the 2LS to make and run a thread
145  * appropriate for running func(arg) in the GCC/glibc environment.  The thread
146  * will have TLS and not be detached. */
147 struct uthread *uthread_create(void *(*func)(void *), void *arg);
148 void uthread_detach(struct uthread *uth);
149 void uthread_join(struct uthread *uth, void **retval_loc);
150 void uthread_join_arr(struct uth_join_request reqs[], size_t nr_req);
151 void uthread_sched_yield(void);
152 struct uthread *uthread_self(void);
153
154 /* Call this when you are done with a uthread, forever, but before you free it */
155 void uthread_cleanup(struct uthread *uthread);
156 void uthread_runnable(struct uthread *uthread);
157 void uthread_yield(bool save_state, void (*yield_func)(struct uthread*, void*),
158                    void *yield_arg);
159 void uthread_sleep(unsigned int seconds);
160 void uthread_usleep(unsigned int usecs);
161 void __attribute__((noreturn)) uthread_sleep_forever(void);
162 void uthread_has_blocked(struct uthread *uthread, uth_sync_t sync, int flags);
163 void uthread_paused(struct uthread *uthread);
164
165 /* Utility functions */
166 bool __check_preempt_pending(uint32_t vcoreid); /* careful: check the code */
167 void uth_disable_notifs(void);
168 void uth_enable_notifs(void);
169
170 /* Helpers, which the 2LS can call */
171 void __block_uthread_on_async_sysc(struct uthread *uth);
172 void highjack_current_uthread(struct uthread *uthread);
173 struct uthread *stop_current_uthread(void);
174 void __attribute__((noreturn)) run_current_uthread(void);
175 void __attribute__((noreturn)) run_uthread(struct uthread *uthread);
176 void __attribute__((noreturn)) uth_2ls_thread_exit(void *retval);
177
178 /* Asking for trouble with this API, when we just want stacktop (or whatever
179  * the SP will be). */
180 static inline void init_uthread_ctx(struct uthread *uth, void (*entry)(void),
181                                     void *stack_bottom, uint32_t size)
182 {
183         init_user_ctx(&uth->u_ctx, (long)entry, (long)(stack_bottom) + size);
184 }
185
186 /* When we look at the current_uthread, its context might be in the uthread
187  * struct or it might be in VCPD.  This returns a pointer to the right place. */
188 static inline struct user_context *get_cur_uth_ctx(void)
189 {
190         if (current_uthread->flags & UTHREAD_SAVED)
191                 return &current_uthread->u_ctx;
192         else
193                 return &vcpd_of(vcore_id())->uthread_ctx;
194 }
195
196 #define uthread_set_tls_var(uth, name, val)                                    \
197 ({                                                                             \
198         typeof(val) __val = val;                                                   \
199         begin_access_tls_vars(((struct uthread*)(uth))->tls_desc);                 \
200         name = __val;                                                              \
201         end_access_tls_vars();                                                     \
202 })
203
204 #define uthread_get_tls_var(uth, name)                                         \
205 ({                                                                             \
206         typeof(name) val;                                                          \
207         begin_access_tls_vars(((struct uthread*)(uth))->tls_desc);                 \
208         val = name;                                                                \
209         end_access_tls_vars();                                                     \
210         val;                                                                       \
211 })
212
213 /* Uthread Mutexes / CVs / etc. */
214
215 typedef struct uth_semaphore uth_semaphore_t;
216 typedef struct uth_semaphore uth_mutex_t;
217 typedef struct uth_recurse_mutex uth_recurse_mutex_t;
218 typedef struct uth_cond_var uth_cond_var_t;
219 typedef struct uth_rwlock uth_rwlock_t;
220
221 struct uth_semaphore {
222         struct spin_pdr_lock            lock;
223         uth_sync_t                                      sync_obj;
224         unsigned int                            count;
225         parlib_once_t                           once_ctl;
226 };
227 #define UTH_SEMAPHORE_INIT(n) { .once_ctl = PARLIB_ONCE_INIT, .count = (n) }
228 #define UTH_MUTEX_INIT { .once_ctl = PARLIB_ONCE_INIT }
229
230 struct uth_recurse_mutex {
231         uth_mutex_t                                     mtx;
232         struct uthread                          *lockholder;
233         unsigned int                            count;
234         parlib_once_t                           once_ctl;
235 };
236 #define UTH_RECURSE_MUTEX_INIT { .once_ctl = PARLIB_ONCE_INIT }
237
238 struct uth_cond_var {
239         struct spin_pdr_lock            lock;
240         uth_sync_t                                      sync_obj;
241         parlib_once_t                           once_ctl;
242 };
243 #define UTH_COND_VAR_INIT { .once_ctl = PARLIB_ONCE_INIT }
244
245 struct uth_rwlock {
246         struct spin_pdr_lock            lock;
247         unsigned int                            nr_readers;
248         bool                                            has_writer;
249         uth_sync_t                                      readers;
250         uth_sync_t                                      writers;
251         parlib_once_t                           once_ctl;
252 };
253 #define UTH_RWLOCK_INIT { .once_ctl = PARLIB_ONCE_INIT }
254
255 void uth_semaphore_init(uth_semaphore_t *sem, unsigned int count);
256 void uth_semaphore_destroy(uth_semaphore_t *sem);
257 uth_semaphore_t *uth_semaphore_alloc(unsigned int count);
258 void uth_semaphore_free(uth_semaphore_t *sem);
259 bool uth_semaphore_timed_down(uth_semaphore_t *sem,
260                               const struct timespec *abs_timeout);
261 void uth_semaphore_down(uth_semaphore_t *sem);
262 bool uth_semaphore_trydown(uth_semaphore_t *sem);
263 void uth_semaphore_up(uth_semaphore_t *sem);
264
265 void uth_mutex_init(uth_mutex_t *m);
266 void uth_mutex_destroy(uth_mutex_t *m);
267 uth_mutex_t *uth_mutex_alloc(void);
268 void uth_mutex_free(uth_mutex_t *m);
269 bool uth_mutex_timed_lock(uth_mutex_t *m, const struct timespec *abs_timeout);
270 void uth_mutex_lock(uth_mutex_t *m);
271 bool uth_mutex_trylock(uth_mutex_t *m);
272 void uth_mutex_unlock(uth_mutex_t *m);
273
274 void uth_recurse_mutex_init(uth_recurse_mutex_t *r_m);
275 void uth_recurse_mutex_destroy(uth_recurse_mutex_t *r_m);
276 uth_recurse_mutex_t *uth_recurse_mutex_alloc(void);
277 void uth_recurse_mutex_free(uth_recurse_mutex_t *r_m);
278 bool uth_recurse_mutex_timed_lock(uth_recurse_mutex_t *m,
279                                   const struct timespec *abs_timeout);
280 void uth_recurse_mutex_lock(uth_recurse_mutex_t *r_m);
281 bool uth_recurse_mutex_trylock(uth_recurse_mutex_t *r_m);
282 void uth_recurse_mutex_unlock(uth_recurse_mutex_t *r_m);
283
284 /* Callers to cv_wait must hold the mutex, which it will atomically wait and
285  * unlock, then relock when it returns.  Callers to signal and broadcast may
286  * hold the mutex, if they choose. */
287 void uth_cond_var_init(uth_cond_var_t *cv);
288 void uth_cond_var_destroy(uth_cond_var_t *cv);
289 uth_cond_var_t *uth_cond_var_alloc(void);
290 void uth_cond_var_free(uth_cond_var_t *cv);
291 bool uth_cond_var_timed_wait(uth_cond_var_t *cv, uth_mutex_t *m,
292                              const struct timespec *abs_timeout);
293 void uth_cond_var_wait(uth_cond_var_t *cv, uth_mutex_t *m);
294 bool uth_cond_var_timed_wait_recurse(uth_cond_var_t *cv,
295                                      uth_recurse_mutex_t *r_mtx,
296                                      const struct timespec *abs_timeout);
297 void uth_cond_var_wait_recurse(uth_cond_var_t *cv, uth_recurse_mutex_t *r_mtx);
298 void uth_cond_var_signal(uth_cond_var_t *cv);
299 void uth_cond_var_broadcast(uth_cond_var_t *cv);
300
301 void uth_rwlock_init(uth_rwlock_t *rwl);
302 void uth_rwlock_destroy(uth_rwlock_t *rwl);
303 uth_rwlock_t *uth_rwlock_alloc(void);
304 void uth_rwlock_free(uth_rwlock_t *rwl);
305 void uth_rwlock_rdlock(uth_rwlock_t *rwl);
306 bool uth_rwlock_try_rdlock(uth_rwlock_t *rwl);
307 void uth_rwlock_wrlock(uth_rwlock_t *rwl);
308 bool uth_rwlock_try_wrlock(uth_rwlock_t *rwl);
309 void uth_rwlock_unlock(uth_rwlock_t *rwl);
310
311 /* Called by gcc to see if we are multithreaded. */
312 bool uth_2ls_is_multithreaded(void);
313
314 __END_DECLS