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