parlib: Add __uth_sync_swap and __uth_sync_is_empty
[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 /* This struct is a blob of sufficient storage to be whatever a 2LS wants for
74  * its thread list structure (e.g., TAILQ, priority queue, RB tree, etc).
75  * Internally, 2LSs and the default implementation use another object type.
76  *
77  * If a 2LS overrides the sync ops and uses its own synchronization, it can
78  * either use the uthread->sync_next field, or add its own field to its thread
79  * structure.
80  *
81  * If we need to increase the size, then do a full rebuild (with a make clean)
82  * of the toolchain.  libgomp and probably c++ threads care about the size of
83  * objects that contain uth_sync_t. */
84 typedef struct __uth_sync_opaque {
85         uint8_t                                         foo[sizeof(uintptr_t) * 2];
86 } __attribute__ ((aligned(sizeof(uintptr_t)))) uth_sync_t;
87
88 /* 2LS-independent synchronization code (e.g. uthread mutexes) uses these
89  * helpers to access 2LS-specific functions.
90  *
91  * Note the spinlock associated with the higher-level sync primitive is held for
92  * these (where applicable). */
93 void __uth_sync_init(uth_sync_t *sync);
94 void __uth_sync_destroy(uth_sync_t *sync);
95 void __uth_sync_enqueue(struct uthread *uth, uth_sync_t *sync);
96 struct uthread *__uth_sync_get_next(uth_sync_t *sync);
97 bool __uth_sync_get_uth(uth_sync_t *sync, struct uthread *uth);
98 void __uth_sync_swap(uth_sync_t *a, uth_sync_t *b);
99 bool __uth_sync_is_empty(uth_sync_t *sync);
100
101 /* 2L-Scheduler operations.  Examples in pthread.c. */
102 struct schedule_ops {
103         /**** These functions must be defined ****/
104         void (*sched_init)(void);
105         void (*sched_entry)(void);
106         void (*thread_runnable)(struct uthread *);
107         void (*thread_paused)(struct uthread *);
108         void (*thread_blockon_sysc)(struct uthread *, void *);
109         void (*thread_has_blocked)(struct uthread *, int);
110         void (*thread_refl_fault)(struct uthread *, struct user_context *);
111         void (*thread_exited)(struct uthread *);
112         struct uthread *(*thread_create)(void *(*)(void *), void *);
113         /**** Defining these functions is optional. ****/
114         void (*sync_init)(uth_sync_t *);
115         void (*sync_destroy)(uth_sync_t *);
116         void (*sync_enqueue)(struct uthread *, uth_sync_t *);
117         struct uthread *(*sync_get_next)(uth_sync_t *);
118         bool (*sync_get_uth)(uth_sync_t *, struct uthread *);
119         void (*sync_swap)(uth_sync_t *, uth_sync_t *);
120         bool (*sync_is_empty)(uth_sync_t *);
121         void (*preempt_pending)(void);
122 };
123 extern struct schedule_ops *sched_ops;
124
125 /* Call this from your 2LS init routines.  Pass it a uthread representing
126  * thread0, your 2LS ops, and your syscall handler + data.
127  *
128  * When it returns, you're in _M mode (thread0 on vcore0) */
129 void uthread_2ls_init(struct uthread *uthread,
130                       void (*handle_sysc)(struct event_msg *, unsigned int,
131                                           void *),
132                       void *data);
133 /* Call this to become an mcp capable of worling with uthreads. */
134 void uthread_mcp_init(void);
135
136 /* Functions to make/manage uthreads.  Can be called by functions such as
137  * pthread_create(), which can wrap these with their own stuff (like attrs,
138  * retvals, etc). */
139
140 struct uth_thread_attr {
141         bool want_tls;          /* default, no */
142         bool detached;          /* default, no */
143 };
144
145 struct uth_join_request {
146         struct uthread                          *uth;
147         void                                            **retval_loc;
148 };
149
150 /* uthread_init() does the uthread initialization of a uthread that the caller
151  * created.  Call this whenever you are "starting over" with a thread.  Pass in
152  * attr, if you want to override any defaults. */
153 void uthread_init(struct uthread *new_thread, struct uth_thread_attr *attr);
154 /* uthread_create() is a front-end for getting the 2LS to make and run a thread
155  * appropriate for running func(arg) in the GCC/glibc environment.  The thread
156  * will have TLS and not be detached. */
157 struct uthread *uthread_create(void *(*func)(void *), void *arg);
158 void uthread_detach(struct uthread *uth);
159 void uthread_join(struct uthread *uth, void **retval_loc);
160 void uthread_join_arr(struct uth_join_request reqs[], size_t nr_req);
161 void uthread_sched_yield(void);
162 struct uthread *uthread_self(void);
163
164 /* Call this when you are done with a uthread, forever, but before you free it */
165 void uthread_cleanup(struct uthread *uthread);
166 void uthread_runnable(struct uthread *uthread);
167 void uthread_yield(bool save_state, void (*yield_func)(struct uthread*, void*),
168                    void *yield_arg);
169 void uthread_sleep(unsigned int seconds);
170 void uthread_usleep(unsigned int usecs);
171 void __attribute__((noreturn)) uthread_sleep_forever(void);
172 void uthread_has_blocked(struct uthread *uthread, int flags);
173 void uthread_paused(struct uthread *uthread);
174
175 /* Utility functions */
176 bool __check_preempt_pending(uint32_t vcoreid); /* careful: check the code */
177 void uth_disable_notifs(void);
178 void uth_enable_notifs(void);
179 void assert_can_block(void);
180
181 /* Helpers, which the 2LS can call */
182 void __block_uthread_on_async_sysc(struct uthread *uth);
183 void highjack_current_uthread(struct uthread *uthread);
184 struct uthread *stop_current_uthread(void);
185 void __attribute__((noreturn)) run_current_uthread(void);
186 void __attribute__((noreturn)) run_uthread(struct uthread *uthread);
187 void __attribute__((noreturn)) uth_2ls_thread_exit(void *retval);
188
189 /* Asking for trouble with this API, when we just want stacktop (or whatever
190  * the SP will be). */
191 static inline void init_uthread_ctx(struct uthread *uth, void (*entry)(void),
192                                     void *stack_bottom, uint32_t size)
193 {
194         init_user_ctx(&uth->u_ctx, (long)entry, (long)(stack_bottom) + size);
195 }
196
197 /* When we look at the current_uthread, its context might be in the uthread
198  * struct or it might be in VCPD.  This returns a pointer to the right place. */
199 static inline struct user_context *get_cur_uth_ctx(void)
200 {
201         if (current_uthread->flags & UTHREAD_SAVED)
202                 return &current_uthread->u_ctx;
203         else
204                 return &vcpd_of(vcore_id())->uthread_ctx;
205 }
206
207 #define uthread_set_tls_var(uth, name, val)                                    \
208 ({                                                                             \
209         typeof(val) __val = val;                                                   \
210         begin_access_tls_vars(((struct uthread*)(uth))->tls_desc);                 \
211         name = __val;                                                              \
212         end_access_tls_vars();                                                     \
213 })
214
215 #define uthread_get_tls_var(uth, name)                                         \
216 ({                                                                             \
217         typeof(name) val;                                                          \
218         begin_access_tls_vars(((struct uthread*)(uth))->tls_desc);                 \
219         val = name;                                                                \
220         end_access_tls_vars();                                                     \
221         val;                                                                       \
222 })
223
224 /* Uthread Mutexes / CVs / etc. */
225
226 typedef struct uth_semaphore uth_semaphore_t;
227 typedef struct uth_semaphore uth_mutex_t;
228 typedef struct uth_recurse_mutex uth_recurse_mutex_t;
229 typedef struct uth_cond_var uth_cond_var_t;
230 typedef struct uth_rwlock uth_rwlock_t;
231
232 struct uth_semaphore {
233         parlib_once_t                           once_ctl;
234         unsigned int                            count;
235         struct spin_pdr_lock            lock;
236         uth_sync_t                                      sync_obj;
237 };
238 #define UTH_SEMAPHORE_INIT(n) { PARLIB_ONCE_INIT, (n) }
239 #define UTH_MUTEX_INIT { PARLIB_ONCE_INIT }
240
241 struct uth_recurse_mutex {
242         parlib_once_t                           once_ctl;
243         uth_mutex_t                                     mtx;
244         struct uthread                          *lockholder;
245         unsigned int                            count;
246 };
247 #define UTH_RECURSE_MUTEX_INIT { PARLIB_ONCE_INIT }
248
249 struct uth_cond_var {
250         parlib_once_t                           once_ctl;
251         struct spin_pdr_lock            lock;
252         uth_sync_t                                      sync_obj;
253 };
254 #define UTH_COND_VAR_INIT { PARLIB_ONCE_INIT }
255
256 struct uth_rwlock {
257         parlib_once_t                           once_ctl;
258         struct spin_pdr_lock            lock;
259         unsigned int                            nr_readers;
260         bool                                            has_writer;
261         uth_sync_t                                      readers;
262         uth_sync_t                                      writers;
263 };
264 #define UTH_RWLOCK_INIT { PARLIB_ONCE_INIT }
265
266 void uth_semaphore_init(uth_semaphore_t *sem, unsigned int count);
267 void uth_semaphore_destroy(uth_semaphore_t *sem);
268 uth_semaphore_t *uth_semaphore_alloc(unsigned int count);
269 void uth_semaphore_free(uth_semaphore_t *sem);
270 bool uth_semaphore_timed_down(uth_semaphore_t *sem,
271                               const struct timespec *abs_timeout);
272 void uth_semaphore_down(uth_semaphore_t *sem);
273 bool uth_semaphore_trydown(uth_semaphore_t *sem);
274 void uth_semaphore_up(uth_semaphore_t *sem);
275
276 void uth_mutex_init(uth_mutex_t *m);
277 void uth_mutex_destroy(uth_mutex_t *m);
278 uth_mutex_t *uth_mutex_alloc(void);
279 void uth_mutex_free(uth_mutex_t *m);
280 bool uth_mutex_timed_lock(uth_mutex_t *m, const struct timespec *abs_timeout);
281 void uth_mutex_lock(uth_mutex_t *m);
282 bool uth_mutex_trylock(uth_mutex_t *m);
283 void uth_mutex_unlock(uth_mutex_t *m);
284
285 void uth_recurse_mutex_init(uth_recurse_mutex_t *r_m);
286 void uth_recurse_mutex_destroy(uth_recurse_mutex_t *r_m);
287 uth_recurse_mutex_t *uth_recurse_mutex_alloc(void);
288 void uth_recurse_mutex_free(uth_recurse_mutex_t *r_m);
289 bool uth_recurse_mutex_timed_lock(uth_recurse_mutex_t *m,
290                                   const struct timespec *abs_timeout);
291 void uth_recurse_mutex_lock(uth_recurse_mutex_t *r_m);
292 bool uth_recurse_mutex_trylock(uth_recurse_mutex_t *r_m);
293 void uth_recurse_mutex_unlock(uth_recurse_mutex_t *r_m);
294
295 /* Callers to cv_wait must hold the mutex, which it will atomically wait and
296  * unlock, then relock when it returns.  Callers to signal and broadcast may
297  * hold the mutex, if they choose. */
298 void uth_cond_var_init(uth_cond_var_t *cv);
299 void uth_cond_var_destroy(uth_cond_var_t *cv);
300 uth_cond_var_t *uth_cond_var_alloc(void);
301 void uth_cond_var_free(uth_cond_var_t *cv);
302 bool uth_cond_var_timed_wait(uth_cond_var_t *cv, uth_mutex_t *m,
303                              const struct timespec *abs_timeout);
304 void uth_cond_var_wait(uth_cond_var_t *cv, uth_mutex_t *m);
305 bool uth_cond_var_timed_wait_recurse(uth_cond_var_t *cv,
306                                      uth_recurse_mutex_t *r_mtx,
307                                      const struct timespec *abs_timeout);
308 void uth_cond_var_wait_recurse(uth_cond_var_t *cv, uth_recurse_mutex_t *r_mtx);
309 void uth_cond_var_signal(uth_cond_var_t *cv);
310 void uth_cond_var_broadcast(uth_cond_var_t *cv);
311
312 void uth_rwlock_init(uth_rwlock_t *rwl);
313 void uth_rwlock_destroy(uth_rwlock_t *rwl);
314 uth_rwlock_t *uth_rwlock_alloc(void);
315 void uth_rwlock_free(uth_rwlock_t *rwl);
316 void uth_rwlock_rdlock(uth_rwlock_t *rwl);
317 bool uth_rwlock_try_rdlock(uth_rwlock_t *rwl);
318 void uth_rwlock_wrlock(uth_rwlock_t *rwl);
319 bool uth_rwlock_try_wrlock(uth_rwlock_t *rwl);
320 void uth_rwlock_unlock(uth_rwlock_t *rwl);
321
322 /* Called by gcc to see if we are multithreaded. */
323 bool uth_2ls_is_multithreaded(void);
324
325 __END_DECLS