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