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
28 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
29 #include <mach/mach.h>
30 #include <mach/mach_error.h>
31 #include <mach/mach_types.h>
35 #include "validate.h" /* for BINDING_STACK_SIZE etc */
38 #include "target-arch-os.h"
42 #include "genesis/cons.h"
43 #include "genesis/fdefn.h"
44 #include "interr.h" /* for lose() */
46 #include "gc-internal.h"
48 #include "pseudo-atomic.h"
49 #include "interrupt.h"
52 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD)
53 # define IMMEDIATE_POST_MORTEM
56 #if defined(LISP_FEATURE_DARWIN) && defined(LISP_FEATURE_SB_THREAD)
57 #define DELAY_THREAD_POST_MORTEM 5
58 #define LOCK_CREATE_THREAD
61 #ifdef LISP_FEATURE_FREEBSD
62 #define CREATE_CLEANUP_THREAD
63 #define LOCK_CREATE_THREAD
66 #ifdef LISP_FEATURE_SB_THREAD
67 struct thread_post_mortem {
68 #ifdef DELAY_THREAD_POST_MORTEM
69 struct thread_post_mortem *next;
71 os_thread_t os_thread;
72 pthread_attr_t *os_attr;
73 os_vm_address_t os_address;
76 #ifdef DELAY_THREAD_POST_MORTEM
77 static int pending_thread_post_mortem_count = 0;
78 pthread_mutex_t thread_post_mortem_lock = PTHREAD_MUTEX_INITIALIZER;
80 static struct thread_post_mortem * volatile pending_thread_post_mortem = 0;
83 int dynamic_values_bytes=TLS_SIZE*sizeof(lispobj); /* same for all threads */
84 struct thread *all_threads;
85 extern struct interrupt_data * global_interrupt_data;
87 #ifdef LISP_FEATURE_SB_THREAD
88 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
89 #ifdef LOCK_CREATE_THREAD
90 static pthread_mutex_t create_thread_lock = PTHREAD_MUTEX_INITIALIZER;
92 #ifdef LISP_FEATURE_GCC_TLS
93 __thread struct thread *current_thread;
95 pthread_key_t lisp_thread = 0;
98 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
99 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs)
100 # ifdef LISP_FEATURE_X86_64
101 __attribute__((sysv_abi))
107 link_thread(struct thread *th)
109 if (all_threads) all_threads->prev=th;
110 th->next=all_threads;
115 #ifdef LISP_FEATURE_SB_THREAD
117 unlink_thread(struct thread *th)
120 th->prev->next = th->next;
122 all_threads = th->next;
124 th->next->prev = th->prev;
127 #ifndef LISP_FEATURE_SB_SAFEPOINT
128 /* Only access thread state with blockables blocked. */
130 thread_state(struct thread *thread)
134 block_blockable_signals(NULL, &old);
135 os_sem_wait(thread->state_sem, "thread_state");
136 state = thread->state;
137 os_sem_post(thread->state_sem, "thread_state");
138 thread_sigmask(SIG_SETMASK, &old, NULL);
143 set_thread_state(struct thread *thread, lispobj state)
145 int i, waitcount = 0;
147 block_blockable_signals(NULL, &old);
148 os_sem_wait(thread->state_sem, "set_thread_state");
149 if (thread->state != state) {
150 if ((STATE_STOPPED==state) ||
151 (STATE_DEAD==state)) {
152 waitcount = thread->state_not_running_waitcount;
153 thread->state_not_running_waitcount = 0;
154 for (i=0; i<waitcount; i++)
155 os_sem_post(thread->state_not_running_sem, "set_thread_state (not running)");
157 if ((STATE_RUNNING==state) ||
158 (STATE_DEAD==state)) {
159 waitcount = thread->state_not_stopped_waitcount;
160 thread->state_not_stopped_waitcount = 0;
161 for (i=0; i<waitcount; i++)
162 os_sem_post(thread->state_not_stopped_sem, "set_thread_state (not stopped)");
164 thread->state = state;
166 os_sem_post(thread->state_sem, "set_thread_state");
167 thread_sigmask(SIG_SETMASK, &old, NULL);
171 wait_for_thread_state_change(struct thread *thread, lispobj state)
175 block_blockable_signals(NULL, &old);
177 os_sem_wait(thread->state_sem, "wait_for_thread_state_change");
178 if (thread->state == state) {
181 wait_sem = thread->state_not_running_sem;
182 thread->state_not_running_waitcount++;
185 wait_sem = thread->state_not_stopped_sem;
186 thread->state_not_stopped_waitcount++;
189 lose("Invalid state in wait_for_thread_state_change: "OBJ_FMTX"\n", state);
194 os_sem_post(thread->state_sem, "wait_for_thread_state_change");
196 os_sem_wait(wait_sem, "wait_for_thread_state_change");
199 thread_sigmask(SIG_SETMASK, &old, NULL);
201 #endif /* sb-safepoint */
202 #endif /* sb-thread */
205 initial_thread_trampoline(struct thread *th)
208 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
209 lispobj *args = NULL;
211 #ifdef LISP_FEATURE_SB_THREAD
212 pthread_setspecific(lisp_thread, (void *)1);
214 #if defined(THREADS_USING_GCSIGNAL) && defined(LISP_FEATURE_PPC)
215 /* SIG_STOP_FOR_GC defaults to blocked on PPC? */
216 unblock_gc_signals(0,0);
218 function = th->no_tls_value_marker;
219 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
220 if(arch_os_thread_init(th)==0) return 1;
222 th->os_thread=thread_self();
223 #ifndef LISP_FEATURE_WIN32
224 protect_control_stack_hard_guard_page(1, NULL);
226 protect_binding_stack_hard_guard_page(1, NULL);
227 protect_alien_stack_hard_guard_page(1, NULL);
228 #ifndef LISP_FEATURE_WIN32
229 protect_control_stack_guard_page(1, NULL);
231 protect_binding_stack_guard_page(1, NULL);
232 protect_alien_stack_guard_page(1, NULL);
234 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
235 return call_into_lisp_first_time(function,args,0);
237 return funcall0(function);
241 #ifdef LISP_FEATURE_SB_THREAD
243 # if defined(IMMEDIATE_POST_MORTEM)
246 * If this feature is set, we are running on a stack managed by the OS,
247 * and no fancy delays are required for anything. Just do it.
250 schedule_thread_post_mortem(struct thread *corpse)
252 pthread_detach(pthread_self());
253 gc_assert(!pthread_attr_destroy(corpse->os_attr));
254 free(corpse->os_attr);
255 #if defined(LISP_FEATURE_WIN32)
256 os_invalidate_free(corpse->os_address, THREAD_STRUCT_SIZE);
258 os_invalidate(corpse->os_address, THREAD_STRUCT_SIZE);
264 /* THREAD POST MORTEM CLEANUP
266 * Memory allocated for the thread stacks cannot be reclaimed while
267 * the thread is still alive, so we need a mechanism for post mortem
268 * cleanups. FIXME: We actually have three, for historical reasons as
269 * the saying goes. Do we really need three? Nikodemus guesses that
270 * not anymore, now that we properly call pthread_attr_destroy before
271 * freeing the stack. */
273 static struct thread_post_mortem *
274 plan_thread_post_mortem(struct thread *corpse)
277 struct thread_post_mortem *post_mortem = malloc(sizeof(struct thread_post_mortem));
278 gc_assert(post_mortem);
279 post_mortem->os_thread = corpse->os_thread;
280 post_mortem->os_attr = corpse->os_attr;
281 post_mortem->os_address = corpse->os_address;
282 #ifdef DELAY_THREAD_POST_MORTEM
283 post_mortem->next = NULL;
287 /* FIXME: When does this happen? */
293 perform_thread_post_mortem(struct thread_post_mortem *post_mortem)
295 #ifdef CREATE_POST_MORTEM_THREAD
296 pthread_detach(pthread_self());
299 gc_assert(!pthread_join(post_mortem->os_thread, NULL));
300 gc_assert(!pthread_attr_destroy(post_mortem->os_attr));
301 free(post_mortem->os_attr);
302 os_invalidate(post_mortem->os_address, THREAD_STRUCT_SIZE);
308 schedule_thread_post_mortem(struct thread *corpse)
310 struct thread_post_mortem *post_mortem = NULL;
312 post_mortem = plan_thread_post_mortem(corpse);
314 #ifdef DELAY_THREAD_POST_MORTEM
315 pthread_mutex_lock(&thread_post_mortem_lock);
316 /* First stick the new post mortem to the end of the queue. */
317 if (pending_thread_post_mortem) {
318 struct thread_post_mortem *next = pending_thread_post_mortem;
322 next->next = post_mortem;
324 pending_thread_post_mortem = post_mortem;
326 /* Then, if there are enough things in the queue, clean up one
327 * from the head -- or increment the count, and null out the
328 * post_mortem we have. */
329 if (pending_thread_post_mortem_count > DELAY_THREAD_POST_MORTEM) {
330 post_mortem = pending_thread_post_mortem;
331 pending_thread_post_mortem = post_mortem->next;
333 pending_thread_post_mortem_count++;
336 pthread_mutex_unlock(&thread_post_mortem_lock);
337 /* Finally run, the cleanup, if any. */
338 perform_thread_post_mortem(post_mortem);
339 #elif defined(CREATE_POST_MORTEM_THREAD)
340 gc_assert(!pthread_create(&thread, NULL, perform_thread_post_mortem, post_mortem));
342 post_mortem = (struct thread_post_mortem *)
343 swap_lispobjs((lispobj *)(void *)&pending_thread_post_mortem,
344 (lispobj)post_mortem);
345 perform_thread_post_mortem(post_mortem);
350 # endif /* !IMMEDIATE_POST_MORTEM */
352 /* Note: scribble must be stack-allocated */
354 init_new_thread(struct thread *th, init_thread_data *scribble, int guardp)
358 pthread_setspecific(lisp_thread, (void *)1);
359 if(arch_os_thread_init(th)==0) {
360 /* FIXME: handle error */
361 lose("arch_os_thread_init failed\n");
364 th->os_thread=thread_self();
366 protect_control_stack_guard_page(1, NULL);
367 protect_binding_stack_guard_page(1, NULL);
368 protect_alien_stack_guard_page(1, NULL);
369 /* Since GC can only know about this thread from the all_threads
370 * list and we're just adding this thread to it, there is no
371 * danger of deadlocking even with SIG_STOP_FOR_GC blocked (which
373 #ifdef LISP_FEATURE_SB_SAFEPOINT
374 *th->csp_around_foreign_call = (lispobj)scribble;
376 lock_ret = pthread_mutex_lock(&all_threads_lock);
377 gc_assert(lock_ret == 0);
379 lock_ret = pthread_mutex_unlock(&all_threads_lock);
380 gc_assert(lock_ret == 0);
382 /* Kludge: Changed the order of some steps between the safepoint/
383 * non-safepoint versions of this code. Can we unify this more?
385 #ifdef LISP_FEATURE_SB_SAFEPOINT
387 gc_state_wait(GC_NONE);
389 push_gcing_safety(&scribble->safety);
394 undo_init_new_thread(struct thread *th, init_thread_data *scribble)
398 /* Kludge: Changed the order of some steps between the safepoint/
399 * non-safepoint versions of this code. Can we unify this more?
401 #ifdef LISP_FEATURE_SB_SAFEPOINT
402 block_blockable_signals(0, 0);
403 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
404 pop_gcing_safety(&scribble->safety);
405 lock_ret = pthread_mutex_lock(&all_threads_lock);
406 gc_assert(lock_ret == 0);
408 lock_ret = pthread_mutex_unlock(&all_threads_lock);
409 gc_assert(lock_ret == 0);
412 block_blockable_signals(0, 0);
413 set_thread_state(th, STATE_DEAD);
415 /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
416 * thread, but since we are already dead it won't wait long. */
417 lock_ret = pthread_mutex_lock(&all_threads_lock);
418 gc_assert(lock_ret == 0);
420 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
422 pthread_mutex_unlock(&all_threads_lock);
423 gc_assert(lock_ret == 0);
426 if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
427 #ifndef LISP_FEATURE_SB_SAFEPOINT
428 os_sem_destroy(th->state_sem);
429 os_sem_destroy(th->state_not_running_sem);
430 os_sem_destroy(th->state_not_stopped_sem);
433 #if defined(LISP_FEATURE_WIN32)
434 free((os_vm_address_t)th->interrupt_data);
436 os_invalidate((os_vm_address_t)th->interrupt_data,
437 (sizeof (struct interrupt_data)));
440 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
441 mach_lisp_thread_destroy(th);
444 #if defined(LISP_FEATURE_WIN32)
447 (int) (sizeof(th->private_events.events)/
448 sizeof(th->private_events.events[0])); ++i) {
449 CloseHandle(th->private_events.events[i]);
451 TlsSetValue(OUR_TLS_INDEX,NULL);
454 /* Undo the association of the current pthread to its `struct thread',
455 * such that we can call arch_os_get_current_thread() later in this
456 * thread and cleanly get back NULL. */
457 #ifdef LISP_FEATURE_GCC_TLS
458 current_thread = NULL;
460 pthread_setspecific(specials, NULL);
463 schedule_thread_post_mortem(th);
466 /* this is the first thing that runs in the child (which is why the
467 * silly calling convention). Basically it calls the user's requested
468 * lisp function after doing arch_os_thread_init and whatever other
469 * bookkeeping needs to be done
472 new_thread_trampoline(struct thread *th)
475 init_thread_data scribble;
477 FSHOW((stderr,"/creating thread %lu\n", thread_self()));
478 check_deferrables_blocked_or_lose(0);
479 #ifndef LISP_FEATURE_SB_SAFEPOINT
480 check_gc_signals_unblocked_or_lose(0);
483 lispobj function = th->no_tls_value_marker;
484 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
485 init_new_thread(th, &scribble, 1);
486 result = funcall0(function);
487 undo_init_new_thread(th, &scribble);
489 FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
493 # ifdef LISP_FEATURE_SB_SAFEPOINT
494 static struct thread *create_thread_struct(lispobj);
497 attach_os_thread(init_thread_data *scribble)
499 os_thread_t os = pthread_self();
500 odxprint(misc, "attach_os_thread: attaching to %p", os);
502 struct thread *th = create_thread_struct(NIL);
503 block_deferrable_signals(0, &scribble->oldset);
504 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
505 /* We don't actually want a pthread_attr here, but rather than add
506 * `if's to the post-mostem, let's just keep that code happy by
507 * keeping it initialized: */
508 pthread_attr_init(th->os_attr);
510 #ifndef LISP_FEATURE_WIN32
511 /* On windows, arch_os_thread_init will take care of finding the
514 int pthread_getattr_np(pthread_t, pthread_attr_t *);
515 pthread_getattr_np(os, &attr);
518 pthread_attr_getstack(&attr, &stack_addr, &stack_size);
519 th->control_stack_start = stack_addr;
520 th->control_stack_end = (void *) (((uintptr_t) stack_addr) + stack_size);
523 init_new_thread(th, scribble, 0);
525 /* We will be calling into Lisp soon, and the functions being called
526 * recklessly ignore the comment in target-thread which says that we
527 * must be careful to not cause GC while initializing a new thread.
528 * Since we first need to create a fresh thread object, it's really
529 * tempting to just perform such unsafe allocation though. So let's
530 * at least try to suppress GC before consing, and hope that it
532 SetSymbolValue(GC_INHIBIT, T, th);
535 = (uword_t) th->control_stack_end - (uword_t) th->control_stack_start;
536 odxprint(misc, "attach_os_thread: attached %p as %p (0x%lx bytes stack)",
537 os, th, (long) stacksize);
541 detach_os_thread(init_thread_data *scribble)
543 struct thread *th = arch_os_get_current_thread();
544 odxprint(misc, "detach_os_thread: detaching");
546 undo_init_new_thread(th, scribble);
548 odxprint(misc, "deattach_os_thread: detached");
549 pthread_setspecific(lisp_thread, (void *)0);
550 thread_sigmask(SIG_SETMASK, &scribble->oldset, 0);
552 # endif /* safepoint */
554 #endif /* LISP_FEATURE_SB_THREAD */
557 free_thread_struct(struct thread *th)
559 #if defined(LISP_FEATURE_WIN32)
560 if (th->interrupt_data) {
561 os_invalidate_free((os_vm_address_t) th->interrupt_data,
562 (sizeof (struct interrupt_data)));
564 os_invalidate_free((os_vm_address_t) th->os_address,
567 if (th->interrupt_data)
568 os_invalidate((os_vm_address_t) th->interrupt_data,
569 (sizeof (struct interrupt_data)));
570 os_invalidate((os_vm_address_t) th->os_address,
575 #ifdef LISP_FEATURE_SB_THREAD
576 /* FIXME: should be MAX_INTERRUPTS -1 ? */
577 const unsigned int tls_index_start =
578 MAX_INTERRUPTS + sizeof(struct thread)/sizeof(lispobj);
581 /* this is called from any other thread to create the new one, and
582 * initialize all parts of it that can be initialized from another
586 static struct thread *
587 create_thread_struct(lispobj initial_function) {
588 union per_thread_data *per_thread;
589 struct thread *th=0; /* subdue gcc */
591 void *aligned_spaces=0;
592 #if defined(LISP_FEATURE_SB_THREAD) || defined(LISP_FEATURE_WIN32)
596 /* May as well allocate all the spaces at once: it saves us from
597 * having to decide what to do if only some of the allocations
598 * succeed. SPACES must be appropriately aligned, since the GC
599 * expects the control stack to start at a page boundary -- and
600 * the OS may have even more rigorous requirements. We can't rely
601 * on the alignment passed from os_validate, since that might
602 * assume the current (e.g. 4k) pagesize, while we calculate with
603 * the biggest (e.g. 64k) pagesize allowed by the ABI. */
604 spaces=os_validate(0, THREAD_STRUCT_SIZE);
607 /* Aligning up is safe as THREAD_STRUCT_SIZE has
608 * THREAD_ALIGNMENT_BYTES padding. */
609 aligned_spaces = (void *)((((uword_t)(char *)spaces)
610 + THREAD_ALIGNMENT_BYTES-1)
611 &~(uword_t)(THREAD_ALIGNMENT_BYTES-1));
614 thread_control_stack_size+
617 per_thread=(union per_thread_data *)
618 (csp_page + THREAD_CSP_PAGE_SIZE);
619 struct nonpointer_thread_data *nonpointer_data
620 = (void *) &per_thread->dynamic_values[TLS_SIZE];
622 #ifdef LISP_FEATURE_SB_THREAD
623 for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
624 per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
625 if (all_threads == 0) {
626 if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
627 SetSymbolValue(FREE_TLS_INDEX,tls_index_start << WORD_SHIFT,0);
628 SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
630 #define STATIC_TLS_INIT(sym,field) \
631 ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
632 (THREAD_SLOT_OFFSET_WORDS(field) << WORD_SHIFT)
634 STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
635 #ifdef BINDING_STACK_POINTER
636 STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
638 STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
639 STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
641 STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
643 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
644 STATIC_TLS_INIT(PSEUDO_ATOMIC_BITS,pseudo_atomic_bits);
646 #undef STATIC_TLS_INIT
650 th=&per_thread->thread;
651 th->os_address = spaces;
652 th->control_stack_start = aligned_spaces;
653 th->binding_stack_start=
654 (lispobj*)((void*)th->control_stack_start+thread_control_stack_size);
655 th->control_stack_end = th->binding_stack_start;
656 th->control_stack_guard_page_protected = T;
657 th->alien_stack_start=
658 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
659 set_binding_stack_pointer(th,th->binding_stack_start);
663 #ifdef LISP_FEATURE_SB_SAFEPOINT
664 # ifdef LISP_FEATURE_WIN32
665 th->carried_base_pointer = 0;
667 # ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
668 th->pc_around_foreign_call = 0;
670 th->csp_around_foreign_call = csp_page;
673 #ifdef LISP_FEATURE_SB_THREAD
674 /* Contrary to the "allocate all the spaces at once" comment above,
675 * the os_attr is allocated separately. We cannot put it into the
676 * nonpointer data, because it's used for post_mortem and freed
678 th->os_attr=malloc(sizeof(pthread_attr_t));
679 th->nonpointer_data = nonpointer_data;
680 # ifndef LISP_FEATURE_SB_SAFEPOINT
681 th->state_sem=&nonpointer_data->state_sem;
682 th->state_not_running_sem=&nonpointer_data->state_not_running_sem;
683 th->state_not_stopped_sem=&nonpointer_data->state_not_stopped_sem;
684 os_sem_init(th->state_sem, 1);
685 os_sem_init(th->state_not_running_sem, 0);
686 os_sem_init(th->state_not_stopped_sem, 0);
688 th->state_not_running_waitcount = 0;
689 th->state_not_stopped_waitcount = 0;
691 th->state=STATE_RUNNING;
692 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
693 th->alien_stack_pointer=((void *)th->alien_stack_start
694 + ALIEN_STACK_SIZE-N_WORD_BYTES);
696 th->alien_stack_pointer=((void *)th->alien_stack_start);
698 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64) || defined(LISP_FEATURE_SB_THREAD)
699 th->pseudo_atomic_bits=0;
701 #ifdef LISP_FEATURE_GENCGC
702 gc_set_region_empty(&th->alloc_region);
704 #ifdef LISP_FEATURE_SB_THREAD
705 /* This parallels the same logic in globals.c for the
706 * single-threaded foreign_function_call_active, KLUDGE and
708 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
709 th->foreign_function_call_active = 0;
711 th->foreign_function_call_active = 1;
715 #ifndef LISP_FEATURE_SB_THREAD
716 /* the tls-points-into-struct-thread trick is only good for threaded
717 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
718 * appropriate values from struct thread here, and make sure that
719 * we use the appropriate SymbolValue macros to access any of the
720 * variable quantities from the C runtime. It's not quite OAOOM,
721 * it just feels like it */
722 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
723 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
724 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
725 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
726 SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
727 SetSymbolValue(PSEUDO_ATOMIC_BITS,(lispobj)th->pseudo_atomic_bits,th);
730 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
731 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
732 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
733 bind_variable(INTERRUPT_PENDING, NIL,th);
734 bind_variable(INTERRUPTS_ENABLED,T,th);
735 bind_variable(ALLOW_WITH_INTERRUPTS,T,th);
736 bind_variable(GC_PENDING,NIL,th);
737 bind_variable(ALLOC_SIGNAL,NIL,th);
738 #ifdef PINNED_OBJECTS
739 bind_variable(PINNED_OBJECTS,NIL,th);
741 #ifdef LISP_FEATURE_SB_THREAD
742 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
744 #if defined(LISP_FEATURE_SB_SAFEPOINT)
745 bind_variable(GC_SAFE,NIL,th);
746 bind_variable(IN_SAFEPOINT,NIL,th);
748 #ifdef LISP_FEATURE_SB_THRUPTION
749 bind_variable(THRUPTION_PENDING,NIL,th);
750 bind_variable(RESTART_CLUSTERS,NIL,th);
752 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
753 access_control_stack_pointer(th)=th->control_stack_start;
756 #if defined(LISP_FEATURE_WIN32)
757 th->interrupt_data = (struct interrupt_data *)
758 calloc((sizeof (struct interrupt_data)),1);
760 th->interrupt_data = (struct interrupt_data *)
761 os_validate(0,(sizeof (struct interrupt_data)));
763 if (!th->interrupt_data) {
764 free_thread_struct(th);
767 th->interrupt_data->pending_handler = 0;
768 th->interrupt_data->gc_blocked_deferrables = 0;
769 #ifdef GENCGC_IS_PRECISE
770 th->interrupt_data->allocation_trap_context = 0;
772 th->no_tls_value_marker=initial_function;
774 #if defined(LISP_FEATURE_WIN32)
775 for (i = 0; i<sizeof(th->private_events.events)/
776 sizeof(th->private_events.events[0]); ++i) {
777 th->private_events.events[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
779 th->synchronous_io_handle_and_flag = 0;
785 void create_initial_thread(lispobj initial_function) {
786 struct thread *th=create_thread_struct(initial_function);
787 #ifdef LISP_FEATURE_SB_THREAD
788 pthread_key_create(&lisp_thread, 0);
791 initial_thread_trampoline(th); /* no return */
792 } else lose("can't create initial thread\n");
795 #ifdef LISP_FEATURE_SB_THREAD
797 #ifndef __USE_XOPEN2K
798 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
802 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
804 /* The new thread inherits the restrictive signal mask set here,
805 * and enables signals again when it is set up properly. */
808 int retcode = 0, initcode;
810 FSHOW_SIGNAL((stderr,"/create_os_thread: creating new thread\n"));
812 /* Blocking deferrable signals is enough, no need to block
813 * SIG_STOP_FOR_GC because the child process is not linked onto
814 * all_threads until it's ready. */
815 block_deferrable_signals(0, &oldset);
817 #ifdef LOCK_CREATE_THREAD
818 retcode = pthread_mutex_lock(&create_thread_lock);
819 gc_assert(retcode == 0);
820 FSHOW_SIGNAL((stderr,"/create_os_thread: got lock\n"));
823 if((initcode = pthread_attr_init(th->os_attr)) ||
824 /* call_into_lisp_first_time switches the stack for the initial
825 * thread. For the others, we use this. */
826 #if defined(LISP_FEATURE_WIN32)
827 (pthread_attr_setstacksize(th->os_attr, thread_control_stack_size)) ||
829 (pthread_attr_setstack(th->os_attr,th->control_stack_start,
830 thread_control_stack_size)) ||
832 (retcode = pthread_create
833 (kid_tid,th->os_attr,(void *(*)(void *))new_thread_trampoline,th))) {
834 FSHOW_SIGNAL((stderr, "init = %d\n", initcode));
835 FSHOW_SIGNAL((stderr, "pthread_create returned %d, errno %d\n",
838 perror("create_os_thread");
843 #ifdef LOCK_CREATE_THREAD
844 retcode = pthread_mutex_unlock(&create_thread_lock);
845 gc_assert(retcode == 0);
846 FSHOW_SIGNAL((stderr,"/create_os_thread: released lock\n"));
848 thread_sigmask(SIG_SETMASK,&oldset,0);
852 os_thread_t create_thread(lispobj initial_function) {
853 struct thread *th, *thread = arch_os_get_current_thread();
854 os_thread_t kid_tid = 0;
856 /* Must defend against async unwinds. */
857 if (SymbolValue(INTERRUPTS_ENABLED, thread) != NIL)
858 lose("create_thread is not safe when interrupts are enabled.\n");
860 /* Assuming that a fresh thread struct has no lisp objects in it,
861 * linking it to all_threads can be left to the thread itself
862 * without fear of gc lossage. initial_function violates this
863 * assumption and must stay pinned until the child starts up. */
864 th = create_thread_struct(initial_function);
865 if (th && !create_os_thread(th,&kid_tid)) {
866 free_thread_struct(th);
872 /* stopping the world is a two-stage process. From this thread we signal
873 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
874 * the usual pseudo-atomic checks (we don't want to stop a thread while
875 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
878 * (With SB-SAFEPOINT, see the definitions in safepoint.c instead.)
880 #ifndef LISP_FEATURE_SB_SAFEPOINT
882 /* To avoid deadlocks when gc stops the world all clients of each
883 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
884 * holding the lock, but they must agree on which. */
885 void gc_stop_the_world()
887 struct thread *p,*th=arch_os_get_current_thread();
888 int status, lock_ret;
889 #ifdef LOCK_CREATE_THREAD
890 /* KLUDGE: Stopping the thread during pthread_create() causes deadlock
892 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on create_thread_lock\n"));
893 lock_ret = pthread_mutex_lock(&create_thread_lock);
894 gc_assert(lock_ret == 0);
895 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got create_thread_lock\n"));
897 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock\n"));
898 /* keep threads from starting while the world is stopped. */
899 lock_ret = pthread_mutex_lock(&all_threads_lock); \
900 gc_assert(lock_ret == 0);
902 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock\n"));
903 /* stop all other threads by sending them SIG_STOP_FOR_GC */
904 for(p=all_threads; p; p=p->next) {
905 gc_assert(p->os_thread != 0);
906 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: thread=%lu, state=%x\n",
907 p->os_thread, thread_state(p)));
908 if((p!=th) && ((thread_state(p)==STATE_RUNNING))) {
909 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending thread %lu\n",
911 /* We already hold all_thread_lock, P can become DEAD but
912 * cannot exit, ergo it's safe to use pthread_kill. */
913 status=pthread_kill(p->os_thread,SIG_STOP_FOR_GC);
915 /* This thread has exited. */
916 gc_assert(thread_state(p)==STATE_DEAD);
918 lose("cannot send suspend thread=%lu: %d, %s\n",
919 p->os_thread,status,strerror(status));
923 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
924 for(p=all_threads;p;p=p->next) {
928 "/gc_stop_the_world: waiting for thread=%lu: state=%x\n",
929 p->os_thread, thread_state(p)));
930 wait_for_thread_state_change(p, STATE_RUNNING);
931 if (p->state == STATE_RUNNING)
932 lose("/gc_stop_the_world: unexpected state");
935 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
938 void gc_start_the_world()
940 struct thread *p,*th=arch_os_get_current_thread();
942 /* if a resumed thread creates a new thread before we're done with
943 * this loop, the new thread will get consed on the front of
944 * all_threads, but it won't have been stopped so won't need
946 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
947 for(p=all_threads;p;p=p->next) {
948 gc_assert(p->os_thread!=0);
950 lispobj state = thread_state(p);
951 if (state != STATE_DEAD) {
952 if(state != STATE_STOPPED) {
953 lose("gc_start_the_world: wrong thread state is %d\n",
954 fixnum_value(state));
956 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
958 set_thread_state(p, STATE_RUNNING);
963 lock_ret = pthread_mutex_unlock(&all_threads_lock);
964 gc_assert(lock_ret == 0);
965 #ifdef LOCK_CREATE_THREAD
966 lock_ret = pthread_mutex_unlock(&create_thread_lock);
967 gc_assert(lock_ret == 0);
970 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
973 #endif /* !LISP_FEATURE_SB_SAFEPOINT */
974 #endif /* !LISP_FEATURE_SB_THREAD */
979 #ifdef LISP_FEATURE_SB_THREAD
980 return sched_yield();
987 wake_thread(os_thread_t os_thread)
989 #if defined(LISP_FEATURE_WIN32)
990 return kill_safely(os_thread, 1);
991 #elif !defined(LISP_FEATURE_SB_THRUPTION)
992 return kill_safely(os_thread, SIGPIPE);
994 return wake_thread_posix(os_thread);
998 /* If the thread id given does not belong to a running thread (it has
999 * exited or never even existed) pthread_kill _may_ fail with ESRCH,
1000 * but it is also allowed to just segfault, see
1001 * <http://udrepper.livejournal.com/16844.html>.
1003 * Relying on thread ids can easily backfire since ids are recycled
1004 * (NPTL recycles them extremely fast) so a signal can be sent to
1005 * another process if the one it was sent to exited.
1007 * For these reasons, we must make sure that the thread is still alive
1008 * when the pthread_kill is called and return if the thread is
1011 * Note (DFL, 2011-06-22): At the time of writing, this function is only
1012 * used for INTERRUPT-THREAD, hence the wake_thread special-case for
1015 kill_safely(os_thread_t os_thread, int signal)
1017 FSHOW_SIGNAL((stderr,"/kill_safely: %lu, %d\n", os_thread, signal));
1019 #ifdef LISP_FEATURE_SB_THREAD
1021 struct thread *thread;
1022 /* Frequent special case: resignalling to self. The idea is
1023 * that leave_region safepoint will acknowledge the signal, so
1024 * there is no need to take locks, roll thread to safepoint
1026 /* Kludge (on safepoint builds): At the moment, this isn't just
1027 * an optimization; rather it masks the fact that
1028 * gc_stop_the_world() grabs the all_threads mutex without
1029 * releasing it, and since we're not using recursive pthread
1030 * mutexes, the pthread_mutex_lock() around the all_threads loop
1031 * would go wrong. Why are we running interruptions while
1032 * stopping the world though? Test case is (:ASYNC-UNWIND
1033 * :SPECIALS), especially with s/10/100/ in both loops. */
1034 if (os_thread == pthread_self()) {
1035 pthread_kill(os_thread, signal);
1036 #ifdef LISP_FEATURE_WIN32
1037 check_pending_thruptions(NULL);
1042 /* pthread_kill is not async signal safe and we don't want to be
1043 * interrupted while holding the lock. */
1044 block_deferrable_signals(0, &oldset);
1045 pthread_mutex_lock(&all_threads_lock);
1046 for (thread = all_threads; thread; thread = thread->next) {
1047 if (thread->os_thread == os_thread) {
1048 int status = pthread_kill(os_thread, signal);
1050 lose("kill_safely: pthread_kill failed with %d\n", status);
1051 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THRUPTION)
1052 wake_thread_win32(thread);
1057 pthread_mutex_unlock(&all_threads_lock);
1058 thread_sigmask(SIG_SETMASK,&oldset,0);
1063 #elif defined(LISP_FEATURE_WIN32)
1068 lose("kill_safely: who do you want to kill? %d?\n", os_thread);
1069 /* Dubious (as in don't know why it works) workaround for the
1070 * signal sometimes not being generated on darwin. */
1071 #ifdef LISP_FEATURE_DARWIN
1074 sigprocmask(SIG_BLOCK, &deferrable_sigset, &oldset);
1075 status = raise(signal);
1076 sigprocmask(SIG_SETMASK,&oldset,0);
1079 status = raise(signal);
1084 lose("cannot raise signal %d, %d %s\n",
1085 signal, status, strerror(errno));