2 * This software is part of the SBCL system. See the README file for
5 * This software is derived from the CMU CL system, which was
6 * written at Carnegie Mellon University and released into the
7 * public domain. The software is in the public domain and is
8 * provided with absolutely no warranty. See the COPYING and CREDITS
9 * files for more information.
17 #ifndef LISP_FEATURE_WIN32
23 #include <sys/types.h>
24 #ifndef LISP_FEATURE_WIN32
29 #include "validate.h" /* for CONTROL_STACK_SIZE etc */
33 #include "target-arch-os.h"
37 #include "genesis/cons.h"
38 #include "genesis/fdefn.h"
39 #include "interr.h" /* for lose() */
40 #include "gc-internal.h"
42 #ifdef LISP_FEATURE_WIN32
44 * Win32 doesn't have SIGSTKSZ, and we're not switching stacks anyway,
45 * so define it arbitrarily
50 #if defined(LISP_FEATURE_DARWIN) && defined(LISP_FEATURE_SB_THREAD)
51 #define QUEUE_FREEABLE_THREAD_STACKS
54 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
56 struct freeable_stack {
57 #ifdef QUEUE_FREEABLE_THREAD_STACKS
58 struct freeable_stack *next;
60 os_thread_t os_thread;
61 os_vm_address_t stack;
65 #ifdef QUEUE_FREEABLE_THREAD_STACKS
66 static struct freeable_stack * volatile freeable_stack_queue = 0;
67 static int freeable_stack_count = 0;
68 pthread_mutex_t freeable_stack_lock = PTHREAD_MUTEX_INITIALIZER;
70 static struct freeable_stack * volatile freeable_stack = 0;
73 int dynamic_values_bytes=4096*sizeof(lispobj); /* same for all threads */
74 struct thread * volatile all_threads;
75 extern struct interrupt_data * global_interrupt_data;
77 #ifdef LISP_FEATURE_SB_THREAD
78 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
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);
86 link_thread(struct thread *th)
88 if (all_threads) all_threads->prev=th;
94 #ifdef LISP_FEATURE_SB_THREAD
96 unlink_thread(struct thread *th)
99 th->prev->next = th->next;
101 all_threads = th->next;
103 th->next->prev = th->prev;
108 initial_thread_trampoline(struct thread *th)
111 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
112 lispobj *args = NULL;
114 function = th->no_tls_value_marker;
115 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
116 if(arch_os_thread_init(th)==0) return 1;
118 th->os_thread=thread_self();
119 #ifndef LISP_FEATURE_WIN32
120 protect_control_stack_guard_page(1);
123 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
124 return call_into_lisp_first_time(function,args,0);
126 return funcall0(function);
130 #define THREAD_STRUCT_SIZE (THREAD_CONTROL_STACK_SIZE + BINDING_STACK_SIZE + \
131 ALIEN_STACK_SIZE + dynamic_values_bytes + \
134 #ifdef LISP_FEATURE_SB_THREAD
136 #ifdef QUEUE_FREEABLE_THREAD_STACKS
138 queue_freeable_thread_stack(struct thread *thread_to_be_cleaned_up)
140 if (thread_to_be_cleaned_up) {
141 pthread_mutex_lock(&freeable_stack_lock);
142 if (freeable_stack_queue) {
143 struct freeable_stack *new_freeable_stack = 0, *next;
144 next = freeable_stack_queue;
148 new_freeable_stack = (struct freeable_stack *)
149 os_validate(0, sizeof(struct freeable_stack));
150 new_freeable_stack->next = NULL;
151 new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
152 new_freeable_stack->stack = (os_vm_address_t)
153 thread_to_be_cleaned_up->control_stack_start;
154 next->next = new_freeable_stack;
155 freeable_stack_count++;
157 struct freeable_stack *new_freeable_stack = 0;
158 new_freeable_stack = (struct freeable_stack *)
159 os_validate(0, sizeof(struct freeable_stack));
160 new_freeable_stack->next = NULL;
161 new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
162 new_freeable_stack->stack = (os_vm_address_t)
163 thread_to_be_cleaned_up->control_stack_start;
164 freeable_stack_queue = new_freeable_stack;
165 freeable_stack_count++;
167 pthread_mutex_unlock(&freeable_stack_lock);
171 #define FREEABLE_STACK_QUEUE_SIZE 4
174 free_freeable_stacks() {
175 if (freeable_stack_queue && (freeable_stack_count > FREEABLE_STACK_QUEUE_SIZE)) {
176 struct freeable_stack* old;
177 pthread_mutex_lock(&freeable_stack_lock);
178 old = freeable_stack_queue;
179 freeable_stack_queue = old->next;
180 freeable_stack_count--;
181 gc_assert(pthread_join(old->os_thread, NULL) == 0);
182 FSHOW((stderr, "freeing thread %x stack\n", old->os_thread));
183 os_invalidate(old->stack, THREAD_STRUCT_SIZE);
184 os_invalidate((os_vm_address_t)old, sizeof(struct freeable_stack));
185 pthread_mutex_unlock(&freeable_stack_lock);
191 free_thread_stack_later(struct thread *thread_to_be_cleaned_up)
193 struct freeable_stack *new_freeable_stack = 0;
194 if (thread_to_be_cleaned_up) {
195 new_freeable_stack = (struct freeable_stack *)
196 os_validate(0, sizeof(struct freeable_stack));
197 new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
198 new_freeable_stack->stack = (os_vm_address_t)
199 thread_to_be_cleaned_up->control_stack_start;
201 new_freeable_stack = (struct freeable_stack *)
202 swap_lispobjs((lispobj *)(void *)&freeable_stack,
203 (lispobj)new_freeable_stack);
204 if (new_freeable_stack) {
205 FSHOW((stderr,"/reaping %p\n", (void*) new_freeable_stack->os_thread));
206 /* Under NPTL pthread_join really waits until the thread
207 * exists and the stack can be safely freed. This is sadly not
208 * mandated by the pthread spec. */
209 gc_assert(pthread_join(new_freeable_stack->os_thread, NULL) == 0);
210 os_invalidate(new_freeable_stack->stack, THREAD_STRUCT_SIZE);
211 os_invalidate((os_vm_address_t) new_freeable_stack,
212 sizeof(struct freeable_stack));
217 /* this is the first thing that runs in the child (which is why the
218 * silly calling convention). Basically it calls the user's requested
219 * lisp function after doing arch_os_thread_init and whatever other
220 * bookkeeping needs to be done
223 new_thread_trampoline(struct thread *th)
226 int result, lock_ret;
227 FSHOW((stderr,"/creating thread %lu\n", thread_self()));
228 function = th->no_tls_value_marker;
229 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
230 if(arch_os_thread_init(th)==0) {
231 /* FIXME: handle error */
232 lose("arch_os_thread_init failed\n");
235 th->os_thread=thread_self();
236 protect_control_stack_guard_page(1);
237 /* Since GC can only know about this thread from the all_threads
238 * list and we're just adding this thread to it there is no danger
239 * of deadlocking even with SIG_STOP_FOR_GC blocked (which it is
241 lock_ret = pthread_mutex_lock(&all_threads_lock);
242 gc_assert(lock_ret == 0);
244 lock_ret = pthread_mutex_unlock(&all_threads_lock);
245 gc_assert(lock_ret == 0);
247 result = funcall0(function);
248 th->state=STATE_DEAD;
250 /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
251 * thread, but since we are already dead it won't wait long. */
252 lock_ret = pthread_mutex_lock(&all_threads_lock);
253 gc_assert(lock_ret == 0);
255 gc_alloc_update_page_tables(0, &th->alloc_region);
257 pthread_mutex_unlock(&all_threads_lock);
258 gc_assert(lock_ret == 0);
260 if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
261 os_invalidate((os_vm_address_t)th->interrupt_data,
262 (sizeof (struct interrupt_data)));
264 #ifdef QUEUE_FREEABLE_THREAD_STACKS
265 queue_freeable_thread_stack(th);
267 free_thread_stack_later(th);
270 FSHOW((stderr,"/exiting thread %p\n", thread_self()));
274 #endif /* LISP_FEATURE_SB_THREAD */
277 free_thread_struct(struct thread *th)
279 if (th->interrupt_data)
280 os_invalidate((os_vm_address_t) th->interrupt_data,
281 (sizeof (struct interrupt_data)));
282 os_invalidate((os_vm_address_t) th->control_stack_start,
286 /* this is called from any other thread to create the new one, and
287 * initialize all parts of it that can be initialized from another
291 static struct thread *
292 create_thread_struct(lispobj initial_function) {
293 union per_thread_data *per_thread;
294 struct thread *th=0; /* subdue gcc */
296 #ifdef LISP_FEATURE_SB_THREAD
300 /* may as well allocate all the spaces at once: it saves us from
301 * having to decide what to do if only some of the allocations
303 spaces=os_validate(0, THREAD_STRUCT_SIZE);
306 per_thread=(union per_thread_data *)
308 THREAD_CONTROL_STACK_SIZE+
312 #ifdef LISP_FEATURE_SB_THREAD
313 for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
314 per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
315 if (all_threads == 0) {
316 if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
319 /* FIXME: should be MAX_INTERRUPTS -1 ? */
320 make_fixnum(MAX_INTERRUPTS+
321 sizeof(struct thread)/sizeof(lispobj)),
323 SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
325 #define STATIC_TLS_INIT(sym,field) \
326 ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
327 make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
329 STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
330 STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
331 STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
332 STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
333 STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
334 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
335 STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
336 STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
338 #undef STATIC_TLS_INIT
342 th=&per_thread->thread;
343 th->control_stack_start = spaces;
344 th->binding_stack_start=
345 (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
346 th->control_stack_end = th->binding_stack_start;
347 th->alien_stack_start=
348 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
349 th->binding_stack_pointer=th->binding_stack_start;
352 th->state=STATE_RUNNING;
353 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
354 th->alien_stack_pointer=((void *)th->alien_stack_start
355 + ALIEN_STACK_SIZE-N_WORD_BYTES);
357 th->alien_stack_pointer=((void *)th->alien_stack_start);
359 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
360 th->pseudo_atomic_interrupted=0;
361 th->pseudo_atomic_atomic=0;
363 #ifdef LISP_FEATURE_GENCGC
364 gc_set_region_empty(&th->alloc_region);
367 #ifndef LISP_FEATURE_SB_THREAD
368 /* the tls-points-into-struct-thread trick is only good for threaded
369 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
370 * appropriate values from struct thread here, and make sure that
371 * we use the appropriate SymbolValue macros to access any of the
372 * variable quantities from the C runtime. It's not quite OAOOM,
373 * it just feels like it */
374 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
375 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
376 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
377 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
378 SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
379 SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
380 SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
381 SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
383 current_binding_stack_pointer=th->binding_stack_pointer;
384 current_control_stack_pointer=th->control_stack_start;
387 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
388 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
389 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
390 bind_variable(INTERRUPT_PENDING, NIL,th);
391 bind_variable(INTERRUPTS_ENABLED,T,th);
392 bind_variable(GC_PENDING,NIL,th);
393 #ifdef LISP_FEATURE_SB_THREAD
394 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
397 th->interrupt_data = (struct interrupt_data *)
398 os_validate(0,(sizeof (struct interrupt_data)));
399 if (!th->interrupt_data) {
400 free_thread_struct(th);
403 th->interrupt_data->pending_handler = 0;
404 th->no_tls_value_marker=initial_function;
408 void create_initial_thread(lispobj initial_function) {
409 struct thread *th=create_thread_struct(initial_function);
411 initial_thread_trampoline(th); /* no return */
412 } else lose("can't create initial thread\n");
415 #ifdef LISP_FEATURE_SB_THREAD
417 #ifndef __USE_XOPEN2K
418 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
422 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
424 /* The new thread inherits the restrictive signal mask set here,
425 * and enables signals again when it is set up properly. */
427 sigset_t newset,oldset;
429 int retcode, initcode, sizecode, addrcode;
431 FSHOW_SIGNAL((stderr,"/create_os_thread: creating new thread\n"));
433 sigemptyset(&newset);
434 /* Blocking deferrable signals is enough, no need to block
435 * SIG_STOP_FOR_GC because the child process is not linked onto
436 * all_threads until it's ready. */
437 sigaddset_deferrable(&newset);
438 thread_sigmask(SIG_BLOCK, &newset, &oldset);
440 #if defined(LISP_FEATURE_DARWIN)
441 #define CONTROL_STACK_ADJUST 8192 /* darwin wants page-aligned stacks */
443 #define CONTROL_STACK_ADJUST 16
446 if((initcode = pthread_attr_init(&attr)) ||
447 /* FIXME: why do we even have this in the first place? */
448 (pthread_attr_setstack(&attr,th->control_stack_start,
449 THREAD_CONTROL_STACK_SIZE-CONTROL_STACK_ADJUST)) ||
450 #undef CONTROL_STACK_ADJUST
451 (retcode = pthread_create
452 (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th))) {
453 FSHOW_SIGNAL((stderr, "init, size, addr = %d, %d, %d\n", initcode, sizecode, addrcode));
454 FSHOW_SIGNAL((stderr, printf("pthread_create returned %d, errno %d\n", retcode, errno)));
455 FSHOW_SIGNAL((stderr, "wanted stack size %d, min stack size %d\n",
456 THREAD_CONTROL_STACK_SIZE-16, PTHREAD_STACK_MIN));
458 perror("create_os_thread");
462 #ifdef QUEUE_FREEABLE_THREAD_STACKS
463 free_freeable_stacks();
465 thread_sigmask(SIG_SETMASK,&oldset,0);
469 os_thread_t create_thread(lispobj initial_function) {
473 /* Assuming that a fresh thread struct has no lisp objects in it,
474 * linking it to all_threads can be left to the thread itself
475 * without fear of gc lossage. initial_function violates this
476 * assumption and must stay pinned until the child starts up. */
477 th = create_thread_struct(initial_function);
480 if (create_os_thread(th,&kid_tid)) {
483 free_thread_struct(th);
488 /* Send the signo to os_thread, retry if the rt signal queue is
490 static int kill_thread_safely(os_thread_t os_thread, int signo)
493 /* The man page does not mention EAGAIN as a valid return value
494 * for either pthread_kill or kill. But that's theory, this is
495 * practice. By waiting here we assume that the delivery of this
496 * signal is not necessary for the delivery of the signals in the
497 * queue. In other words, we _assume_ there are no deadlocks. */
498 while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
499 /* wait a bit then try again in the hope of the rt signal
500 * queue not being full */
501 FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
502 /* FIXME: some kind of backoff (random, exponential) would be
509 int signal_interrupt_thread(os_thread_t os_thread)
511 int status = kill_thread_safely(os_thread, SIG_INTERRUPT_THREAD);
514 } else if (status == ESRCH) {
517 lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s\n",
518 os_thread, status, strerror(status));
522 /* stopping the world is a two-stage process. From this thread we signal
523 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
524 * the usual pseudo-atomic checks (we don't want to stop a thread while
525 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
528 /* To avoid deadlocks when gc stops the world all clients of each
529 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
530 * holding the lock, but they must agree on which. */
531 void gc_stop_the_world()
533 struct thread *p,*th=arch_os_get_current_thread();
534 int status, lock_ret;
535 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
537 /* keep threads from starting while the world is stopped. */
538 lock_ret = pthread_mutex_lock(&all_threads_lock); \
539 gc_assert(lock_ret == 0);
541 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
543 /* stop all other threads by sending them SIG_STOP_FOR_GC */
544 for(p=all_threads; p; p=p->next) {
545 gc_assert(p->os_thread != 0);
546 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: p->state: %x\n", p->state));
547 if((p!=th) && ((p->state==STATE_RUNNING))) {
548 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %x, os_thread %x\n",
550 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
552 /* This thread has exited. */
553 gc_assert(p->state==STATE_DEAD);
555 lose("cannot send suspend thread=%lu: %d, %s\n",
556 p->os_thread,status,strerror(status));
560 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
561 /* wait for the running threads to stop or finish */
562 for(p=all_threads;p;) {
563 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: th: %p, p: %p\n", th, p));
564 if((p!=th) && (p->state==STATE_RUNNING)) {
570 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
573 void gc_start_the_world()
575 struct thread *p,*th=arch_os_get_current_thread();
576 int status, lock_ret;
577 /* if a resumed thread creates a new thread before we're done with
578 * this loop, the new thread will get consed on the front of
579 * all_threads, but it won't have been stopped so won't need
581 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
582 for(p=all_threads;p;p=p->next) {
583 gc_assert(p->os_thread!=0);
584 if((p!=th) && (p->state!=STATE_DEAD)) {
585 if(p->state!=STATE_SUSPENDED) {
586 lose("gc_start_the_world: wrong thread state is %d\n",
587 fixnum_value(p->state));
589 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
591 p->state=STATE_RUNNING;
593 #if defined(SIG_RESUME_FROM_GC)
594 status=kill_thread_safely(p->os_thread,SIG_RESUME_FROM_GC);
596 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
599 lose("cannot resume thread=%lu: %d, %s\n",
600 p->os_thread,status,strerror(status));
604 /* If we waited here until all threads leave STATE_SUSPENDED, then
605 * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
606 * performance implications, but does away with the 'rt signal
607 * queue full' problem. */
609 lock_ret = pthread_mutex_unlock(&all_threads_lock);
610 gc_assert(lock_ret == 0);
612 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));