0.9.5.34:
[sbcl/eslaughter.git] / src / runtime / thread.c
blobc6d2ad59a32b33e89ff4ea55e3240f946085c7bc
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <sched.h>
5 #include <signal.h>
6 #include <stddef.h>
7 #include <errno.h>
8 #include <sys/types.h>
9 #include <sys/wait.h>
11 #include "sbcl.h"
12 #include "runtime.h"
13 #include "validate.h" /* for CONTROL_STACK_SIZE etc */
14 #include "alloc.h"
15 #include "thread.h"
16 #include "arch.h"
17 #include "target-arch-os.h"
18 #include "os.h"
19 #include "globals.h"
20 #include "dynbind.h"
21 #include "genesis/cons.h"
22 #include "genesis/fdefn.h"
23 #include "interr.h" /* for lose() */
24 #include "gc-internal.h"
26 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
28 struct freeable_stack {
29 os_thread_t os_thread;
30 os_vm_address_t stack;
33 static struct freeable_stack * volatile freeable_stack = 0;
35 int dynamic_values_bytes=4096*sizeof(lispobj); /* same for all threads */
36 struct thread * volatile all_threads;
37 extern struct interrupt_data * global_interrupt_data;
38 extern int linux_no_threads_p;
40 #ifdef LISP_FEATURE_SB_THREAD
42 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
44 /* When trying to get all_threads_lock one should make sure that
45 * SIG_STOP_FOR_GC is not blocked. Else there would be a possible
46 * deadlock: gc locks it, other thread blocks signals, gc sends stop
47 * request to other thread and waits, other thread blocks on lock. */
48 void check_sig_stop_for_gc_can_arrive_or_lose()
50 /* Get the current sigmask, by blocking the empty set. */
51 sigset_t empty,current;
52 sigemptyset(&empty);
53 thread_sigmask(SIG_BLOCK, &empty, &current);
54 if (sigismember(&current,SIG_STOP_FOR_GC))
55 lose("SIG_STOP_FOR_GC cannot arrive: it is blocked\n");
56 if (SymbolValue(GC_INHIBIT,arch_os_get_current_thread()) != NIL)
57 lose("SIG_STOP_FOR_GC cannot arrive: gc is inhibited\n");
58 if (arch_pseudo_atomic_atomic(NULL))
59 lose("SIG_STOP_FOR_GC cannot arrive: in pseudo atomic\n");
62 #define GET_ALL_THREADS_LOCK(name) \
63 { \
64 sigset_t _newset,_oldset; \
65 sigemptyset(&_newset); \
66 sigaddset_deferrable(&_newset); \
67 thread_sigmask(SIG_BLOCK, &_newset, &_oldset); \
68 check_sig_stop_for_gc_can_arrive_or_lose(); \
69 FSHOW_SIGNAL((stderr,"/%s:waiting on lock=%ld, thread=%lu\n",name, \
70 all_threads_lock,arch_os_get_current_thread()->os_thread)); \
71 pthread_mutex_lock(&all_threads_lock); \
72 FSHOW_SIGNAL((stderr,"/%s:got lock, thread=%lu\n", \
73 name,arch_os_get_current_thread()->os_thread));
75 #define RELEASE_ALL_THREADS_LOCK(name) \
76 FSHOW_SIGNAL((stderr,"/%s:released lock\n",name)); \
77 pthread_mutex_unlock(&all_threads_lock); \
78 thread_sigmask(SIG_SETMASK,&_oldset,0); \
81 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
82 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs);
83 #endif
85 #endif
87 static void
88 link_thread(struct thread *th)
90 if (all_threads) all_threads->prev=th;
91 th->next=all_threads;
92 th->prev=0;
93 all_threads=th;
96 #ifdef LISP_FEATURE_SB_THREAD
97 static void
98 unlink_thread(struct thread *th)
100 if (th->prev)
101 th->prev->next = th->next;
102 else
103 all_threads = th->next;
104 if (th->next)
105 th->next->prev = th->prev;
107 #endif
109 static int
110 initial_thread_trampoline(struct thread *th)
112 lispobj function;
113 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
114 lispobj *args = NULL;
115 #endif
116 function = th->no_tls_value_marker;
117 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
118 if(arch_os_thread_init(th)==0) return 1;
119 link_thread(th);
120 th->os_thread=thread_self();
121 protect_control_stack_guard_page(1);
122 th->state = STATE_RUNNING;
124 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
125 return call_into_lisp_first_time(function,args,0);
126 #else
127 return funcall0(function);
128 #endif
131 #define THREAD_STRUCT_SIZE (THREAD_CONTROL_STACK_SIZE + BINDING_STACK_SIZE + \
132 ALIEN_STACK_SIZE + dynamic_values_bytes + \
133 32 * SIGSTKSZ)
135 #ifdef LISP_FEATURE_SB_THREAD
137 static void
138 free_thread_stack_later(struct thread *thread_to_be_cleaned_up)
140 struct freeable_stack *new_freeable_stack = 0;
141 if (thread_to_be_cleaned_up) {
142 new_freeable_stack = (struct freeable_stack *)
143 os_validate(0, sizeof(struct freeable_stack));
144 new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
145 new_freeable_stack->stack = (os_vm_address_t)
146 thread_to_be_cleaned_up->control_stack_start;
148 new_freeable_stack = (struct freeable_stack *)
149 swap_lispobjs((lispobj *)(void *)&freeable_stack,
150 (lispobj)new_freeable_stack);
151 if (new_freeable_stack) {
152 FSHOW((stderr,"/reaping %lu\n", new_freeable_stack->os_thread));
153 /* Under NPTL pthread_join really waits until the thread
154 * exists and the stack can be safely freed. This is sadly not
155 * mandated by the pthread spec. */
156 gc_assert(pthread_join(new_freeable_stack->os_thread, NULL) == 0);
157 os_invalidate(new_freeable_stack->stack, THREAD_STRUCT_SIZE);
158 os_invalidate((os_vm_address_t) new_freeable_stack,
159 sizeof(struct freeable_stack));
163 /* this is the first thing that runs in the child (which is why the
164 * silly calling convention). Basically it calls the user's requested
165 * lisp function after doing arch_os_thread_init and whatever other
166 * bookkeeping needs to be done
169 new_thread_trampoline(struct thread *th)
171 lispobj function;
172 int result;
173 FSHOW((stderr,"/creating thread %lu\n", thread_self()));
174 function = th->no_tls_value_marker;
175 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
176 if(arch_os_thread_init(th)==0) {
177 /* FIXME: handle error */
178 lose("arch_os_thread_init failed\n");
181 th->os_thread=thread_self();
182 protect_control_stack_guard_page(1);
183 /* This thread is in STATE_STARTING so the GC is not sending it
184 * SIG_STOP_FOR_GC => no danger of deadlocking even with
185 * SIG_STOP_FOR_GC blocked. The lock is acquired in order not to
186 * enter running state with the gc running. */
187 pthread_mutex_lock(&all_threads_lock);
188 th->state = STATE_RUNNING;
189 pthread_mutex_unlock(&all_threads_lock);
190 /* Now that we entered STATE_RUNNING let the gc suspend this
191 * thread. */
193 sigset_t sigset;
194 sigemptyset(&sigset);
195 sigaddset(&sigset, SIG_STOP_FOR_GC);
196 thread_sigmask(SIG_UNBLOCK, &sigset, 0);
199 result = funcall0(function);
200 th->state=STATE_DEAD;
202 /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
203 * thread, but since we are already dead it won't wait long. */
204 pthread_mutex_lock(&all_threads_lock);
205 unlink_thread(th);
206 pthread_mutex_unlock(&all_threads_lock);
208 gc_alloc_update_page_tables(0, &th->alloc_region);
209 if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
210 os_invalidate((os_vm_address_t)th->interrupt_data,
211 (sizeof (struct interrupt_data)));
212 free_thread_stack_later(th);
213 FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
214 return result;
217 #endif /* LISP_FEATURE_SB_THREAD */
219 static void
220 free_thread_struct(struct thread *th)
222 if (th->interrupt_data)
223 os_invalidate((os_vm_address_t) th->interrupt_data,
224 (sizeof (struct interrupt_data)));
225 os_invalidate((os_vm_address_t) th->control_stack_start,
226 THREAD_STRUCT_SIZE);
229 /* this is called from any other thread to create the new one, and
230 * initialize all parts of it that can be initialized from another
231 * thread
234 static struct thread *
235 create_thread_struct(lispobj initial_function) {
236 union per_thread_data *per_thread;
237 struct thread *th=0; /* subdue gcc */
238 void *spaces=0;
240 /* may as well allocate all the spaces at once: it saves us from
241 * having to decide what to do if only some of the allocations
242 * succeed */
243 spaces=os_validate(0, THREAD_STRUCT_SIZE);
244 if(!spaces)
245 return NULL;
246 per_thread=(union per_thread_data *)
247 (spaces+
248 THREAD_CONTROL_STACK_SIZE+
249 BINDING_STACK_SIZE+
250 ALIEN_STACK_SIZE);
252 if(all_threads) {
253 memcpy(per_thread,arch_os_get_current_thread(),
254 dynamic_values_bytes);
255 } else {
256 #ifdef LISP_FEATURE_SB_THREAD
257 int i;
258 for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
259 per_thread->dynamic_values[i]=NO_TLS_VALUE_MARKER_WIDETAG;
260 if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
261 SetSymbolValue
262 (FREE_TLS_INDEX,
263 make_fixnum(MAX_INTERRUPTS+
264 sizeof(struct thread)/sizeof(lispobj)),
266 SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
268 #define STATIC_TLS_INIT(sym,field) \
269 ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
270 make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
272 STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
273 STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
274 STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
275 STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
276 STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
277 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
278 STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
279 STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
280 #endif
281 #undef STATIC_TLS_INIT
282 #endif
285 th=&per_thread->thread;
286 th->control_stack_start = spaces;
287 th->binding_stack_start=
288 (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
289 th->control_stack_end = th->binding_stack_start;
290 th->alien_stack_start=
291 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
292 th->binding_stack_pointer=th->binding_stack_start;
293 th->this=th;
294 th->os_thread=0;
295 th->state=STATE_STARTING;
296 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
297 th->alien_stack_pointer=((void *)th->alien_stack_start
298 + ALIEN_STACK_SIZE-N_WORD_BYTES);
299 #else
300 th->alien_stack_pointer=((void *)th->alien_stack_start);
301 #endif
302 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
303 th->pseudo_atomic_interrupted=0;
304 th->pseudo_atomic_atomic=0;
305 #endif
306 #ifdef LISP_FEATURE_GENCGC
307 gc_set_region_empty(&th->alloc_region);
308 #endif
310 #ifndef LISP_FEATURE_SB_THREAD
311 /* the tls-points-into-struct-thread trick is only good for threaded
312 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
313 * appropriate values from struct thread here, and make sure that
314 * we use the appropriate SymbolValue macros to access any of the
315 * variable quantities from the C runtime. It's not quite OAOOM,
316 * it just feels like it */
317 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
318 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
319 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
320 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
321 SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
322 SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
323 SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
324 SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
325 #else
326 current_binding_stack_pointer=th->binding_stack_pointer;
327 current_control_stack_pointer=th->control_stack_start;
328 #endif
329 #endif
330 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
331 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
332 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
333 bind_variable(INTERRUPT_PENDING, NIL,th);
334 bind_variable(INTERRUPTS_ENABLED,T,th);
335 bind_variable(GC_PENDING,NIL,th);
336 #ifdef LISP_FEATURE_SB_THREAD
337 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
338 #endif
340 th->interrupt_data = (struct interrupt_data *)
341 os_validate(0,(sizeof (struct interrupt_data)));
342 if (!th->interrupt_data) {
343 free_thread_struct(th);
344 return 0;
346 th->interrupt_data->pending_handler = 0;
347 th->no_tls_value_marker=initial_function;
348 return th;
351 void create_initial_thread(lispobj initial_function) {
352 struct thread *th=create_thread_struct(initial_function);
353 if(th) {
354 initial_thread_trampoline(th); /* no return */
355 } else lose("can't create initial thread");
358 #ifdef LISP_FEATURE_SB_THREAD
360 #ifndef __USE_XOPEN2K
361 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
362 size_t __stacksize);
363 #endif
365 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
367 /* The new thread inherits the restrictive signal mask set here,
368 * and enables signals again when it is set up properly. */
369 pthread_attr_t attr;
370 sigset_t newset,oldset;
371 boolean r=1;
372 sigemptyset(&newset);
373 sigaddset_blockable(&newset);
374 thread_sigmask(SIG_BLOCK, &newset, &oldset);
376 if((pthread_attr_init(&attr)) ||
377 (pthread_attr_setstack(&attr,th->control_stack_start,
378 THREAD_CONTROL_STACK_SIZE-16)) ||
379 (pthread_create
380 (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
381 r=0;
382 thread_sigmask(SIG_SETMASK,&oldset,0);
383 return r;
386 os_thread_t create_thread(lispobj initial_function) {
387 struct thread *th;
388 os_thread_t kid_tid;
390 if(linux_no_threads_p) return 0;
392 /* The new thread must be linked immediately onto all_threads for
393 * gc. */
394 GET_ALL_THREADS_LOCK("create_thread")
395 /* If it is too slow most of the allocation/initialization can
396 * be done without the lock. */
397 th = create_thread_struct(initial_function);
398 if (th)
399 link_thread(th);
400 RELEASE_ALL_THREADS_LOCK("create_thread")
401 if(th==0) return 0;
403 if (create_os_thread(th,&kid_tid)) {
404 return kid_tid;
405 } else {
406 GET_ALL_THREADS_LOCK("create_thread")
407 unlink_thread(th);
408 RELEASE_ALL_THREADS_LOCK("create_thread")
409 free_thread_struct(th);
410 return 0;
414 /* Send the signo to os_thread, retry if the rt signal queue is
415 * full. */
416 static int kill_thread_safely(os_thread_t os_thread, int signo)
418 int r;
419 /* The man page does not mention EAGAIN as a valid return value
420 * for either pthread_kill or kill. But that's theory, this is
421 * practice. By waiting here we assume that the delivery of this
422 * signal is not necessary for the delivery of the signals in the
423 * queue. In other words, we _assume_ there are no deadlocks. */
424 while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
425 /* wait a bit then try again in the hope of the rt signal
426 * queue not being full */
427 FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
428 /* FIXME: some kind of backoff (random, exponential) would be
429 * nice. */
430 sleep(1);
432 return r;
435 int signal_interrupt_thread(os_thread_t os_thread)
437 int status = kill_thread_safely(os_thread, SIG_INTERRUPT_THREAD);
438 if (status == 0) {
439 return 0;
440 } else if (status == ESRCH) {
441 return -1;
442 } else {
443 lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s",
444 os_thread, status, strerror(status));
448 /* stopping the world is a two-stage process. From this thread we signal
449 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
450 * the usual pseudo-atomic checks (we don't want to stop a thread while
451 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
454 /* To avoid deadlocks when gc stops the world all clients of each
455 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
456 * holding the lock, but they must agree on which. */
457 void gc_stop_the_world()
459 struct thread *p,*th=arch_os_get_current_thread();
460 int status;
461 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
462 th->os_thread));
463 /* keep threads from starting while the world is stopped. */
464 pthread_mutex_lock(&all_threads_lock); \
465 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
466 th->os_thread));
467 /* stop all other threads by sending them SIG_STOP_FOR_GC */
468 for(p=all_threads; p; p=p->next) {
469 if((p!=th) && ((p->state==STATE_RUNNING))) {
470 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %lu\n",
471 p->os_thread));
472 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
473 if (status==ESRCH) {
474 /* This thread has exited. */
475 gc_assert(p->state==STATE_DEAD);
476 } else if (status) {
477 lose("cannot send suspend thread=%lu: %d, %s",
478 p->os_thread,status,strerror(status));
482 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
483 /* wait for the running threads to stop or finish */
484 for(p=all_threads;p;) {
485 if((p!=th) && (p->state==STATE_RUNNING)) {
486 gc_assert(p->os_thread!=0);
487 sched_yield();
488 } else {
489 p=p->next;
492 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
495 void gc_start_the_world()
497 struct thread *p,*th=arch_os_get_current_thread();
498 int status;
499 /* if a resumed thread creates a new thread before we're done with
500 * this loop, the new thread will get consed on the front of
501 * all_threads, but it won't have been stopped so won't need
502 * restarting */
503 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
504 for(p=all_threads;p;p=p->next) {
505 if((p!=th) && (p->state!=STATE_STARTING) && (p->state!=STATE_DEAD)) {
506 gc_assert(p->os_thread!=0);
507 if(p->state!=STATE_SUSPENDED) {
508 lose("gc_start_the_world: wrong thread state is %d\n",
509 fixnum_value(p->state));
511 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
512 p->os_thread));
513 p->state=STATE_RUNNING;
514 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
515 if (status) {
516 lose("cannot resume thread=%lu: %d, %s",
517 p->os_thread,status,strerror(status));
521 /* If we waited here until all threads leave STATE_SUSPENDED, then
522 * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
523 * performance implications, but does away with the 'rt signal
524 * queue full' problem. */
525 pthread_mutex_unlock(&all_threads_lock); \
526 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
528 #endif