Add a declaration
[sbcl.git] / src / runtime / thread.c
blob1c76f61069892c2b994361cf9789e8a5c4c50279
1 /*
2 * This software is part of the SBCL system. See the README file for
3 * more information.
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.
12 #include "sbcl.h"
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #ifndef LISP_FEATURE_WIN32
18 #include <sched.h>
19 #endif
20 #include <stddef.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #ifndef LISP_FEATURE_WIN32
24 #include <sys/wait.h>
25 #endif
27 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
28 #include <mach/mach.h>
29 #include <mach/mach_error.h>
30 #include <mach/mach_types.h>
31 #endif
33 #include "runtime.h"
34 #include "validate.h" /* for BINDING_STACK_SIZE etc */
35 #include "thread.h"
36 #include "arch.h"
37 #include "target-arch-os.h"
38 #include "os.h"
39 #include "globals.h"
40 #include "dynbind.h"
41 #include "genesis/cons.h"
42 #include "genesis/fdefn.h"
43 #include "interr.h" /* for lose() */
44 #include "alloc.h"
45 #include "gc-internal.h"
46 #include "cpputil.h"
47 #include "pseudo-atomic.h"
48 #include "interrupt.h"
49 #include "lispregs.h"
51 #ifdef LISP_FEATURE_SB_THREAD
53 #ifdef LISP_FEATURE_OPENBSD
54 #include <pthread_np.h>
55 #endif
57 #ifdef LISP_FEATURE_SUNOS
58 #include <thread.h>
59 #endif
61 #ifdef LISP_FEATURE_WIN32
62 # define IMMEDIATE_POST_MORTEM
63 #endif
65 #ifdef LISP_FEATURE_DARWIN
66 #define DELAY_THREAD_POST_MORTEM 5
67 #define LOCK_CREATE_THREAD
68 #endif
70 #endif
72 #if defined(LISP_FEATURE_FREEBSD) || defined(LISP_FEATURE_DRAGONFLY)
73 #define LOCK_CREATE_THREAD
74 #endif
76 #ifdef LISP_FEATURE_SB_THREAD
77 struct thread_post_mortem {
78 #ifdef DELAY_THREAD_POST_MORTEM
79 struct thread_post_mortem *next;
80 #endif
81 os_thread_t os_thread;
82 pthread_attr_t *os_attr;
83 os_vm_address_t os_address;
86 #ifdef DELAY_THREAD_POST_MORTEM
87 static int pending_thread_post_mortem_count = 0;
88 pthread_mutex_t thread_post_mortem_lock = PTHREAD_MUTEX_INITIALIZER;
89 #endif
90 static struct thread_post_mortem * volatile pending_thread_post_mortem = 0;
91 #endif
93 int dynamic_values_bytes=TLS_SIZE*sizeof(lispobj); /* same for all threads */
94 struct thread *all_threads;
95 extern struct interrupt_data * global_interrupt_data;
97 #ifdef LISP_FEATURE_SB_THREAD
98 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
99 #ifdef LOCK_CREATE_THREAD
100 static pthread_mutex_t create_thread_lock = PTHREAD_MUTEX_INITIALIZER;
101 #endif
102 #ifdef LISP_FEATURE_GCC_TLS
103 __thread struct thread *current_thread;
104 #endif
105 pthread_key_t lisp_thread = 0;
106 #endif
108 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
109 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs)
110 # ifdef LISP_FEATURE_X86_64
111 __attribute__((sysv_abi))
112 # endif
114 #endif
116 static void
117 link_thread(struct thread *th)
119 if (all_threads) all_threads->prev=th;
120 th->next=all_threads;
121 th->prev=0;
122 all_threads=th;
125 #ifdef LISP_FEATURE_SB_THREAD
126 static void
127 unlink_thread(struct thread *th)
129 if (th->prev)
130 th->prev->next = th->next;
131 else
132 all_threads = th->next;
133 if (th->next)
134 th->next->prev = th->prev;
137 #ifndef LISP_FEATURE_SB_SAFEPOINT
138 /* Only access thread state with blockables blocked. */
139 lispobj
140 thread_state(struct thread *thread)
142 lispobj state;
143 sigset_t old;
144 block_blockable_signals(NULL, &old);
145 os_sem_wait(thread->state_sem, "thread_state");
146 state = thread->state;
147 os_sem_post(thread->state_sem, "thread_state");
148 thread_sigmask(SIG_SETMASK, &old, NULL);
149 return state;
152 void
153 set_thread_state(struct thread *thread, lispobj state)
155 int i, waitcount = 0;
156 sigset_t old;
157 block_blockable_signals(NULL, &old);
158 os_sem_wait(thread->state_sem, "set_thread_state");
159 if (thread->state != state) {
160 if ((STATE_STOPPED==state) ||
161 (STATE_DEAD==state)) {
162 waitcount = thread->state_not_running_waitcount;
163 thread->state_not_running_waitcount = 0;
164 for (i=0; i<waitcount; i++)
165 os_sem_post(thread->state_not_running_sem, "set_thread_state (not running)");
167 if ((STATE_RUNNING==state) ||
168 (STATE_DEAD==state)) {
169 waitcount = thread->state_not_stopped_waitcount;
170 thread->state_not_stopped_waitcount = 0;
171 for (i=0; i<waitcount; i++)
172 os_sem_post(thread->state_not_stopped_sem, "set_thread_state (not stopped)");
174 thread->state = state;
176 os_sem_post(thread->state_sem, "set_thread_state");
177 thread_sigmask(SIG_SETMASK, &old, NULL);
180 void
181 wait_for_thread_state_change(struct thread *thread, lispobj state)
183 sigset_t old;
184 os_sem_t *wait_sem;
185 block_blockable_signals(NULL, &old);
186 start:
187 os_sem_wait(thread->state_sem, "wait_for_thread_state_change");
188 if (thread->state == state) {
189 switch (state) {
190 case STATE_RUNNING:
191 wait_sem = thread->state_not_running_sem;
192 thread->state_not_running_waitcount++;
193 break;
194 case STATE_STOPPED:
195 wait_sem = thread->state_not_stopped_sem;
196 thread->state_not_stopped_waitcount++;
197 break;
198 default:
199 lose("Invalid state in wait_for_thread_state_change: "OBJ_FMTX"\n", state);
201 } else {
202 wait_sem = NULL;
204 os_sem_post(thread->state_sem, "wait_for_thread_state_change");
205 if (wait_sem) {
206 os_sem_wait(wait_sem, "wait_for_thread_state_change");
207 goto start;
209 thread_sigmask(SIG_SETMASK, &old, NULL);
211 #endif /* sb-safepoint */
212 #endif /* sb-thread */
214 static int
215 initial_thread_trampoline(struct thread *th)
217 lispobj function;
218 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
219 lispobj *args = NULL;
220 #endif
221 #ifdef LISP_FEATURE_SB_THREAD
222 pthread_setspecific(lisp_thread, (void *)1);
223 #endif
224 #if defined(THREADS_USING_GCSIGNAL) && defined(LISP_FEATURE_PPC)
225 /* SIG_STOP_FOR_GC defaults to blocked on PPC? */
226 unblock_gc_signals(0,0);
227 #endif
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) return 1;
231 link_thread(th);
232 th->os_thread=thread_self();
233 #ifndef LISP_FEATURE_WIN32
234 protect_control_stack_hard_guard_page(1, NULL);
235 #endif
236 protect_binding_stack_hard_guard_page(1, NULL);
237 protect_alien_stack_hard_guard_page(1, NULL);
238 #ifndef LISP_FEATURE_WIN32
239 protect_control_stack_guard_page(1, NULL);
240 #endif
241 protect_binding_stack_guard_page(1, NULL);
242 protect_alien_stack_guard_page(1, NULL);
244 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
245 return call_into_lisp_first_time(function,args,0);
246 #else
247 return funcall0(function);
248 #endif
251 #ifdef LISP_FEATURE_SB_THREAD
253 # if defined(IMMEDIATE_POST_MORTEM)
256 * If this feature is set, we are running on a stack managed by the OS,
257 * and no fancy delays are required for anything. Just do it.
259 static void
260 schedule_thread_post_mortem(struct thread *corpse)
262 pthread_detach(pthread_self());
263 gc_assert(!pthread_attr_destroy(corpse->os_attr));
264 free(corpse->os_attr);
265 #if defined(LISP_FEATURE_WIN32)
266 os_invalidate_free(corpse->os_address, THREAD_STRUCT_SIZE);
267 #else
268 os_invalidate(corpse->os_address, THREAD_STRUCT_SIZE);
269 #endif
272 # else
274 /* THREAD POST MORTEM CLEANUP
276 * Memory allocated for the thread stacks cannot be reclaimed while
277 * the thread is still alive, so we need a mechanism for post mortem
278 * cleanups. FIXME: We actually have three, for historical reasons as
279 * the saying goes. Do we really need three? Nikodemus guesses that
280 * not anymore, now that we properly call pthread_attr_destroy before
281 * freeing the stack. */
283 static struct thread_post_mortem *
284 plan_thread_post_mortem(struct thread *corpse)
286 if (corpse) {
287 struct thread_post_mortem *post_mortem = malloc(sizeof(struct thread_post_mortem));
288 gc_assert(post_mortem);
289 post_mortem->os_thread = corpse->os_thread;
290 post_mortem->os_attr = corpse->os_attr;
291 post_mortem->os_address = corpse->os_address;
292 #ifdef DELAY_THREAD_POST_MORTEM
293 post_mortem->next = NULL;
294 #endif
295 return post_mortem;
296 } else {
297 /* FIXME: When does this happen? */
298 return NULL;
302 static void
303 perform_thread_post_mortem(struct thread_post_mortem *post_mortem)
305 #ifdef CREATE_POST_MORTEM_THREAD
306 pthread_detach(pthread_self());
307 #endif
308 if (post_mortem) {
309 gc_assert(!pthread_join(post_mortem->os_thread, NULL));
310 gc_assert(!pthread_attr_destroy(post_mortem->os_attr));
311 free(post_mortem->os_attr);
312 os_invalidate(post_mortem->os_address, THREAD_STRUCT_SIZE);
313 free(post_mortem);
317 static void
318 schedule_thread_post_mortem(struct thread *corpse)
320 struct thread_post_mortem *post_mortem = NULL;
321 if (corpse) {
322 post_mortem = plan_thread_post_mortem(corpse);
324 #ifdef DELAY_THREAD_POST_MORTEM
325 pthread_mutex_lock(&thread_post_mortem_lock);
326 /* First stick the new post mortem to the end of the queue. */
327 if (pending_thread_post_mortem) {
328 struct thread_post_mortem *next = pending_thread_post_mortem;
329 while (next->next) {
330 next = next->next;
332 next->next = post_mortem;
333 } else {
334 pending_thread_post_mortem = post_mortem;
336 /* Then, if there are enough things in the queue, clean up one
337 * from the head -- or increment the count, and null out the
338 * post_mortem we have. */
339 if (pending_thread_post_mortem_count > DELAY_THREAD_POST_MORTEM) {
340 post_mortem = pending_thread_post_mortem;
341 pending_thread_post_mortem = post_mortem->next;
342 } else {
343 pending_thread_post_mortem_count++;
344 post_mortem = NULL;
346 pthread_mutex_unlock(&thread_post_mortem_lock);
347 /* Finally run, the cleanup, if any. */
348 perform_thread_post_mortem(post_mortem);
349 #elif defined(CREATE_POST_MORTEM_THREAD)
350 gc_assert(!pthread_create(&thread, NULL, perform_thread_post_mortem, post_mortem));
351 #else
352 post_mortem = (struct thread_post_mortem *)
353 swap_lispobjs((lispobj *)(void *)&pending_thread_post_mortem,
354 (lispobj)post_mortem);
355 perform_thread_post_mortem(post_mortem);
356 #endif
360 # endif /* !IMMEDIATE_POST_MORTEM */
362 /* Note: scribble must be stack-allocated */
363 static void
364 init_new_thread(struct thread *th, init_thread_data *scribble, int guardp)
366 int lock_ret;
368 pthread_setspecific(lisp_thread, (void *)1);
369 if(arch_os_thread_init(th)==0) {
370 /* FIXME: handle error */
371 lose("arch_os_thread_init failed\n");
374 th->os_thread=thread_self();
375 if (guardp)
376 protect_control_stack_guard_page(1, NULL);
377 protect_binding_stack_guard_page(1, NULL);
378 protect_alien_stack_guard_page(1, NULL);
379 /* Since GC can only know about this thread from the all_threads
380 * list and we're just adding this thread to it, there is no
381 * danger of deadlocking even with SIG_STOP_FOR_GC blocked (which
382 * it is not). */
383 #ifdef LISP_FEATURE_SB_SAFEPOINT
384 *th->csp_around_foreign_call = (lispobj)scribble;
385 #endif
386 lock_ret = pthread_mutex_lock(&all_threads_lock);
387 gc_assert(lock_ret == 0);
388 link_thread(th);
389 lock_ret = pthread_mutex_unlock(&all_threads_lock);
390 gc_assert(lock_ret == 0);
392 /* Kludge: Changed the order of some steps between the safepoint/
393 * non-safepoint versions of this code. Can we unify this more?
395 #ifdef LISP_FEATURE_SB_SAFEPOINT
396 gc_state_lock();
397 gc_state_wait(GC_NONE);
398 gc_state_unlock();
399 push_gcing_safety(&scribble->safety);
400 #endif
403 static void
404 undo_init_new_thread(struct thread *th, init_thread_data *scribble)
406 int lock_ret;
408 /* Kludge: Changed the order of some steps between the safepoint/
409 * non-safepoint versions of this code. Can we unify this more?
411 #ifdef LISP_FEATURE_SB_SAFEPOINT
412 block_blockable_signals(0, 0);
413 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
414 #if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
415 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->sprof_alloc_region);
416 #endif
417 pop_gcing_safety(&scribble->safety);
418 lock_ret = pthread_mutex_lock(&all_threads_lock);
419 gc_assert(lock_ret == 0);
420 unlink_thread(th);
421 lock_ret = pthread_mutex_unlock(&all_threads_lock);
422 gc_assert(lock_ret == 0);
423 #else
424 /* Block GC */
425 block_blockable_signals(0, 0);
426 set_thread_state(th, STATE_DEAD);
428 /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
429 * thread, but since we are already dead it won't wait long. */
430 lock_ret = pthread_mutex_lock(&all_threads_lock);
431 gc_assert(lock_ret == 0);
433 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
434 #if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
435 gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->sprof_alloc_region);
436 #endif
437 unlink_thread(th);
438 pthread_mutex_unlock(&all_threads_lock);
439 gc_assert(lock_ret == 0);
440 #endif
442 if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
443 #ifndef LISP_FEATURE_SB_SAFEPOINT
444 os_sem_destroy(th->state_sem);
445 os_sem_destroy(th->state_not_running_sem);
446 os_sem_destroy(th->state_not_stopped_sem);
447 #endif
449 #if defined(LISP_FEATURE_WIN32)
450 free((os_vm_address_t)th->interrupt_data);
451 #else
452 os_invalidate((os_vm_address_t)th->interrupt_data,
453 (sizeof (struct interrupt_data)));
454 #endif
456 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
457 mach_lisp_thread_destroy(th);
458 #endif
460 #if defined(LISP_FEATURE_WIN32)
461 int i;
462 for (i = 0; i<
463 (int) (sizeof(th->private_events.events)/
464 sizeof(th->private_events.events[0])); ++i) {
465 CloseHandle(th->private_events.events[i]);
467 TlsSetValue(OUR_TLS_INDEX,NULL);
468 #endif
470 /* Undo the association of the current pthread to its `struct thread',
471 * such that we can call arch_os_get_current_thread() later in this
472 * thread and cleanly get back NULL. */
473 #ifdef LISP_FEATURE_GCC_TLS
474 current_thread = NULL;
475 #else
476 pthread_setspecific(specials, NULL);
477 #endif
479 schedule_thread_post_mortem(th);
482 /* this is the first thing that runs in the child (which is why the
483 * silly calling convention). Basically it calls the user's requested
484 * lisp function after doing arch_os_thread_init and whatever other
485 * bookkeeping needs to be done
488 new_thread_trampoline(struct thread *th)
490 int result;
491 init_thread_data scribble;
493 FSHOW((stderr,"/creating thread %lu\n", thread_self()));
494 check_deferrables_blocked_or_lose(0);
495 #ifndef LISP_FEATURE_SB_SAFEPOINT
496 check_gc_signals_unblocked_or_lose(0);
497 #endif
499 lispobj function = th->no_tls_value_marker;
500 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
501 init_new_thread(th, &scribble, 1);
502 result = funcall0(function);
503 undo_init_new_thread(th, &scribble);
505 FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
506 return result;
509 static struct thread *create_thread_struct(lispobj);
511 void
512 attach_os_thread(init_thread_data *scribble)
514 os_thread_t os = pthread_self();
515 odxprint(misc, "attach_os_thread: attaching to %p", os);
517 struct thread *th = create_thread_struct(NIL);
518 block_deferrable_signals(0, &scribble->oldset);
519 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
520 /* We don't actually want a pthread_attr here, but rather than add
521 * `if's to the post-mostem, let's just keep that code happy by
522 * keeping it initialized: */
523 pthread_attr_init(th->os_attr);
525 #ifndef LISP_FEATURE_WIN32
526 /* On windows, arch_os_thread_init will take care of finding the
527 * stack. */
528 void *stack_addr;
529 size_t stack_size;
530 #ifdef LISP_FEATURE_OPENBSD
531 stack_t stack;
532 pthread_stackseg_np(os, &stack);
533 stack_size = stack.ss_size;
534 stack_addr = (void*)((size_t)stack.ss_sp - stack_size);
535 #elif defined LISP_FEATURE_SUNOS
536 stack_t stack;
537 thr_stksegment(&stack);
538 stack_size = stack.ss_size;
539 stack_addr = (void*)((size_t)stack.ss_sp - stack_size);
540 #elif defined(LISP_FEATURE_DARWIN)
541 stack_addr = pthread_get_stackaddr_np(os);
542 stack_size = pthread_get_stacksize_np(os);
543 #else
544 pthread_attr_t attr;
545 #ifdef LISP_FEATURE_FREEBSD
546 pthread_attr_get_np(os, &attr);
547 #else
548 int pthread_getattr_np(pthread_t, pthread_attr_t *);
549 pthread_getattr_np(os, &attr);
550 #endif
551 pthread_attr_getstack(&attr, &stack_addr, &stack_size);
552 #endif
554 th->control_stack_start = stack_addr;
555 th->control_stack_end = (void *) (((uintptr_t) stack_addr) + stack_size);
556 #endif
558 init_new_thread(th, scribble, 0);
560 /* We will be calling into Lisp soon, and the functions being called
561 * recklessly ignore the comment in target-thread which says that we
562 * must be careful to not cause GC while initializing a new thread.
563 * Since we first need to create a fresh thread object, it's really
564 * tempting to just perform such unsafe allocation though. So let's
565 * at least try to suppress GC before consing, and hope that it
566 * works: */
567 bind_variable(GC_INHIBIT, T, th);
569 uword_t stacksize
570 = (uword_t) th->control_stack_end - (uword_t) th->control_stack_start;
571 odxprint(misc, "attach_os_thread: attached %p as %p (0x%lx bytes stack)",
572 os, th, (long) stacksize);
575 void
576 detach_os_thread(init_thread_data *scribble)
578 struct thread *th = arch_os_get_current_thread();
579 odxprint(misc, "detach_os_thread: detaching");
581 undo_init_new_thread(th, scribble);
583 odxprint(misc, "deattach_os_thread: detached");
584 pthread_setspecific(lisp_thread, (void *)0);
585 thread_sigmask(SIG_SETMASK, &scribble->oldset, 0);
588 void
589 callback_wrapper_trampoline(
590 #if !(defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
591 /* On the x86oid backends, the assembly wrapper happens to not pass
592 * in ENTER_ALIEN_CALLBACK explicitly for safepoints. However, the
593 * platforms with precise GC are tricky enough already, and I want
594 * to minimize the read-time conditionals. For those platforms, I'm
595 * only replacing funcall3 with callback_wrapper_trampoline while
596 * keeping the arguments unchanged. --DFL */
597 lispobj __attribute__((__unused__)) fun,
598 #endif
599 lispobj arg0, lispobj arg1, lispobj arg2)
601 #if defined(LISP_FEATURE_WIN32)
602 pthread_np_notice_thread();
603 #endif
604 struct thread* th = arch_os_get_current_thread();
605 if (!th) { /* callback invoked in non-lisp thread */
606 init_thread_data scribble;
607 attach_os_thread(&scribble);
608 funcall3(StaticSymbolFunction(ENTER_FOREIGN_CALLBACK), arg0,arg1,arg2);
609 detach_os_thread(&scribble);
610 return;
613 #ifdef LISP_FEATURE_WIN32
614 /* arg2 is the pointer to a return value, which sits on the stack */
615 th->carried_base_pointer = (os_context_register_t) *(((void**)arg2)-1);
616 #endif
618 #ifdef LISP_FEATURE_SB_SAFEPOINT
619 WITH_GC_AT_SAFEPOINTS_ONLY()
620 #endif
622 funcall3(SymbolValue(ENTER_ALIEN_CALLBACK, 0), arg0, arg1, arg2);
626 #endif /* LISP_FEATURE_SB_THREAD */
628 static void
629 free_thread_struct(struct thread *th)
631 #if defined(LISP_FEATURE_WIN32)
632 if (th->interrupt_data) {
633 os_invalidate_free((os_vm_address_t) th->interrupt_data,
634 (sizeof (struct interrupt_data)));
636 os_invalidate_free((os_vm_address_t) th->os_address,
637 THREAD_STRUCT_SIZE);
638 #else
639 if (th->interrupt_data)
640 os_invalidate((os_vm_address_t) th->interrupt_data,
641 (sizeof (struct interrupt_data)));
642 os_invalidate((os_vm_address_t) th->os_address,
643 THREAD_STRUCT_SIZE);
644 #endif
647 #ifdef LISP_FEATURE_SB_THREAD
648 /* FIXME: should be MAX_INTERRUPTS -1 ? */
649 const unsigned int tls_index_start =
650 MAX_INTERRUPTS + sizeof(struct thread)/sizeof(lispobj);
651 #endif
653 /* this is called from any other thread to create the new one, and
654 * initialize all parts of it that can be initialized from another
655 * thread
658 static struct thread *
659 create_thread_struct(lispobj initial_function) {
660 union per_thread_data *per_thread;
661 struct thread *th=0; /* subdue gcc */
662 void *spaces=0;
663 void *aligned_spaces=0;
664 #if defined(LISP_FEATURE_SB_THREAD) || defined(LISP_FEATURE_WIN32)
665 unsigned int i;
666 #endif
668 /* May as well allocate all the spaces at once: it saves us from
669 * having to decide what to do if only some of the allocations
670 * succeed. SPACES must be appropriately aligned, since the GC
671 * expects the control stack to start at a page boundary -- and
672 * the OS may have even more rigorous requirements. We can't rely
673 * on the alignment passed from os_validate, since that might
674 * assume the current (e.g. 4k) pagesize, while we calculate with
675 * the biggest (e.g. 64k) pagesize allowed by the ABI. */
676 spaces=os_validate(0, THREAD_STRUCT_SIZE);
677 if(!spaces)
678 return NULL;
679 /* Aligning up is safe as THREAD_STRUCT_SIZE has
680 * THREAD_ALIGNMENT_BYTES padding. */
681 aligned_spaces = (void *)((((uword_t)(char *)spaces)
682 + THREAD_ALIGNMENT_BYTES-1)
683 &~(uword_t)(THREAD_ALIGNMENT_BYTES-1));
684 void* csp_page=
685 (aligned_spaces+
686 thread_control_stack_size+
687 BINDING_STACK_SIZE+
688 ALIEN_STACK_SIZE);
689 per_thread=(union per_thread_data *)
690 (csp_page + THREAD_CSP_PAGE_SIZE);
691 struct nonpointer_thread_data *nonpointer_data
692 = (void *) &per_thread->dynamic_values[TLS_SIZE];
694 #ifdef LISP_FEATURE_SB_THREAD
695 for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
696 per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
697 #endif
699 th=&per_thread->thread;
700 th->os_address = spaces;
701 th->control_stack_start = aligned_spaces;
702 th->binding_stack_start=
703 (lispobj*)((void*)th->control_stack_start+thread_control_stack_size);
704 th->control_stack_end = th->binding_stack_start;
705 th->control_stack_guard_page_protected = T;
706 th->alien_stack_start=
707 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
708 set_binding_stack_pointer(th,th->binding_stack_start);
709 th->this=th;
710 th->os_thread=0;
712 #ifdef LISP_FEATURE_SB_SAFEPOINT
713 # ifdef LISP_FEATURE_WIN32
714 th->carried_base_pointer = 0;
715 # endif
716 # ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
717 th->pc_around_foreign_call = 0;
718 # endif
719 th->csp_around_foreign_call = csp_page;
720 #endif
722 #ifdef LISP_FEATURE_SB_THREAD
723 /* Contrary to the "allocate all the spaces at once" comment above,
724 * the os_attr is allocated separately. We cannot put it into the
725 * nonpointer data, because it's used for post_mortem and freed
726 * separately */
727 th->os_attr=malloc(sizeof(pthread_attr_t));
728 th->nonpointer_data = nonpointer_data;
729 # ifndef LISP_FEATURE_SB_SAFEPOINT
730 th->state_sem=&nonpointer_data->state_sem;
731 th->state_not_running_sem=&nonpointer_data->state_not_running_sem;
732 th->state_not_stopped_sem=&nonpointer_data->state_not_stopped_sem;
733 os_sem_init(th->state_sem, 1);
734 os_sem_init(th->state_not_running_sem, 0);
735 os_sem_init(th->state_not_stopped_sem, 0);
736 # endif
737 th->state_not_running_waitcount = 0;
738 th->state_not_stopped_waitcount = 0;
739 #endif
740 th->state=STATE_RUNNING;
741 #ifdef ALIEN_STACK_GROWS_DOWNWARD
742 th->alien_stack_pointer=((void *)th->alien_stack_start
743 + ALIEN_STACK_SIZE-N_WORD_BYTES);
744 #else
745 th->alien_stack_pointer=((void *)th->alien_stack_start);
746 #endif
747 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64) || defined(LISP_FEATURE_SB_THREAD)
748 th->pseudo_atomic_bits=0;
749 #endif
750 #ifdef LISP_FEATURE_GENCGC
751 gc_set_region_empty(&th->alloc_region);
752 # if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
753 gc_set_region_empty(&th->sprof_alloc_region);
754 # endif
755 #endif
756 #ifdef LISP_FEATURE_SB_THREAD
757 /* This parallels the same logic in globals.c for the
758 * single-threaded foreign_function_call_active, KLUDGE and
759 * all. */
760 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
761 th->foreign_function_call_active = 0;
762 #else
763 th->foreign_function_call_active = 1;
764 #endif
765 #endif
767 #ifndef LISP_FEATURE_SB_THREAD
768 /* the tls-points-into-struct-thread trick is only good for threaded
769 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
770 * appropriate values from struct thread here, and make sure that
771 * we use the appropriate SymbolValue macros to access any of the
772 * variable quantities from the C runtime. It's not quite OAOOM,
773 * it just feels like it */
774 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
775 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
776 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
777 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
778 SetSymbolValue(ALIEN_STACK_POINTER,(lispobj)th->alien_stack_pointer,th);
779 SetSymbolValue(PSEUDO_ATOMIC_BITS,(lispobj)th->pseudo_atomic_bits,th);
780 #endif
781 #ifdef PSEUDO_ATOMIC_INTERRUPTED
782 clear_pseudo_atomic_atomic(th);
783 clear_pseudo_atomic_interrupted(th);
784 #endif
785 #endif
786 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
787 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
788 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
789 bind_variable(INTERRUPT_PENDING, NIL,th);
790 bind_variable(INTERRUPTS_ENABLED,T,th);
791 bind_variable(ALLOW_WITH_INTERRUPTS,T,th);
792 bind_variable(GC_PENDING,NIL,th);
793 bind_variable(ALLOC_SIGNAL,NIL,th);
794 #ifdef PINNED_OBJECTS
795 bind_variable(PINNED_OBJECTS,NIL,th);
796 #endif
797 #ifdef LISP_FEATURE_SB_THREAD
798 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
799 #endif
800 #if defined(LISP_FEATURE_SB_SAFEPOINT)
801 bind_variable(GC_SAFE,NIL,th);
802 bind_variable(IN_SAFEPOINT,NIL,th);
803 #endif
804 #ifdef LISP_FEATURE_SB_THRUPTION
805 bind_variable(THRUPTION_PENDING,NIL,th);
806 bind_variable(RESTART_CLUSTERS,NIL,th);
807 #endif
808 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
809 access_control_stack_pointer(th)=th->control_stack_start;
810 #endif
812 #if defined(LISP_FEATURE_WIN32)
813 th->interrupt_data = (struct interrupt_data *)
814 calloc((sizeof (struct interrupt_data)),1);
815 #else
816 th->interrupt_data = (struct interrupt_data *)
817 os_validate(0,(sizeof (struct interrupt_data)));
818 #endif
819 if (!th->interrupt_data) {
820 free_thread_struct(th);
821 return 0;
823 th->interrupt_data->pending_handler = 0;
824 th->interrupt_data->gc_blocked_deferrables = 0;
825 #ifdef GENCGC_IS_PRECISE
826 th->interrupt_data->allocation_trap_context = 0;
827 #endif
828 th->no_tls_value_marker=initial_function;
830 #if defined(LISP_FEATURE_WIN32)
831 for (i = 0; i<sizeof(th->private_events.events)/
832 sizeof(th->private_events.events[0]); ++i) {
833 th->private_events.events[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
835 th->synchronous_io_handle_and_flag = 0;
836 #endif
837 th->stepping = NIL;
838 return th;
841 void create_initial_thread(lispobj initial_function) {
842 struct thread *th=create_thread_struct(initial_function);
843 #ifdef LISP_FEATURE_SB_THREAD
844 pthread_key_create(&lisp_thread, 0);
845 #endif
846 if(th) {
847 initial_thread_trampoline(th); /* no return */
848 } else lose("can't create initial thread\n");
851 #ifdef LISP_FEATURE_SB_THREAD
853 #ifndef __USE_XOPEN2K
854 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
855 size_t __stacksize);
856 #endif
858 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
860 /* The new thread inherits the restrictive signal mask set here,
861 * and enables signals again when it is set up properly. */
862 sigset_t oldset;
863 boolean r=1;
864 int retcode = 0, initcode;
866 FSHOW_SIGNAL((stderr,"/create_os_thread: creating new thread\n"));
868 /* Blocking deferrable signals is enough, no need to block
869 * SIG_STOP_FOR_GC because the child process is not linked onto
870 * all_threads until it's ready. */
871 block_deferrable_signals(0, &oldset);
873 #ifdef LOCK_CREATE_THREAD
874 retcode = pthread_mutex_lock(&create_thread_lock);
875 gc_assert(retcode == 0);
876 FSHOW_SIGNAL((stderr,"/create_os_thread: got lock\n"));
877 #endif
879 if((initcode = pthread_attr_init(th->os_attr)) ||
880 /* call_into_lisp_first_time switches the stack for the initial
881 * thread. For the others, we use this. */
882 #if defined(LISP_FEATURE_WIN32)
883 (pthread_attr_setstacksize(th->os_attr, thread_control_stack_size)) ||
884 #else
885 # if defined(LISP_FEATURE_C_STACK_IS_CONTROL_STACK)
886 (pthread_attr_setstack(th->os_attr,th->control_stack_start,
887 thread_control_stack_size)) ||
888 # else
889 (pthread_attr_setstack(th->os_attr,th->alien_stack_start,
890 ALIEN_STACK_SIZE)) ||
891 # endif
892 #endif
893 (retcode = pthread_create
894 (kid_tid,th->os_attr,(void *(*)(void *))new_thread_trampoline,th))) {
895 FSHOW_SIGNAL((stderr, "init = %d\n", initcode));
896 FSHOW_SIGNAL((stderr, "pthread_create returned %d, errno %d\n",
897 retcode, errno));
898 if(retcode < 0) {
899 perror("create_os_thread");
901 r=0;
904 #ifdef LOCK_CREATE_THREAD
905 retcode = pthread_mutex_unlock(&create_thread_lock);
906 gc_assert(retcode == 0);
907 FSHOW_SIGNAL((stderr,"/create_os_thread: released lock\n"));
908 #endif
909 thread_sigmask(SIG_SETMASK,&oldset,0);
910 return r;
913 os_thread_t create_thread(lispobj initial_function) {
914 struct thread *th, *thread = arch_os_get_current_thread();
915 os_thread_t kid_tid = 0;
917 /* Must defend against async unwinds. */
918 if (SymbolValue(INTERRUPTS_ENABLED, thread) != NIL)
919 lose("create_thread is not safe when interrupts are enabled.\n");
921 /* Assuming that a fresh thread struct has no lisp objects in it,
922 * linking it to all_threads can be left to the thread itself
923 * without fear of gc lossage. initial_function violates this
924 * assumption and must stay pinned until the child starts up. */
925 th = create_thread_struct(initial_function);
926 if (th && !create_os_thread(th,&kid_tid)) {
927 free_thread_struct(th);
928 kid_tid = 0;
930 return kid_tid;
933 /* stopping the world is a two-stage process. From this thread we signal
934 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
935 * the usual pseudo-atomic checks (we don't want to stop a thread while
936 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
939 * (With SB-SAFEPOINT, see the definitions in safepoint.c instead.)
941 #ifndef LISP_FEATURE_SB_SAFEPOINT
943 /* To avoid deadlocks when gc stops the world all clients of each
944 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
945 * holding the lock, but they must agree on which. */
946 void gc_stop_the_world()
948 struct thread *p,*th=arch_os_get_current_thread();
949 int status, lock_ret;
950 #ifdef LOCK_CREATE_THREAD
951 /* KLUDGE: Stopping the thread during pthread_create() causes deadlock
952 * on FreeBSD. */
953 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on create_thread_lock\n"));
954 lock_ret = pthread_mutex_lock(&create_thread_lock);
955 gc_assert(lock_ret == 0);
956 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got create_thread_lock\n"));
957 #endif
958 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock\n"));
959 /* keep threads from starting while the world is stopped. */
960 lock_ret = pthread_mutex_lock(&all_threads_lock); \
961 gc_assert(lock_ret == 0);
963 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock\n"));
964 /* stop all other threads by sending them SIG_STOP_FOR_GC */
965 for(p=all_threads; p; p=p->next) {
966 gc_assert(p->os_thread != 0);
967 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: thread=%lu, state=%x\n",
968 p->os_thread, thread_state(p)));
969 if((p!=th) && ((thread_state(p)==STATE_RUNNING))) {
970 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending thread %lu\n",
971 p->os_thread));
972 /* We already hold all_thread_lock, P can become DEAD but
973 * cannot exit, ergo it's safe to use pthread_kill. */
974 status=pthread_kill(p->os_thread,SIG_STOP_FOR_GC);
975 if (status==ESRCH) {
976 /* This thread has exited. */
977 gc_assert(thread_state(p)==STATE_DEAD);
978 } else if (status) {
979 lose("cannot send suspend thread=%lu: %d, %s\n",
980 p->os_thread,status,strerror(status));
984 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
985 for(p=all_threads;p;p=p->next) {
986 if (p!=th) {
987 FSHOW_SIGNAL
988 ((stderr,
989 "/gc_stop_the_world: waiting for thread=%lu: state=%x\n",
990 p->os_thread, thread_state(p)));
991 wait_for_thread_state_change(p, STATE_RUNNING);
992 if (p->state == STATE_RUNNING)
993 lose("/gc_stop_the_world: unexpected state");
996 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
999 void gc_start_the_world()
1001 struct thread *p,*th=arch_os_get_current_thread();
1002 int lock_ret;
1003 /* if a resumed thread creates a new thread before we're done with
1004 * this loop, the new thread will get consed on the front of
1005 * all_threads, but it won't have been stopped so won't need
1006 * restarting */
1007 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
1008 for(p=all_threads;p;p=p->next) {
1009 gc_assert(p->os_thread!=0);
1010 if (p!=th) {
1011 lispobj state = thread_state(p);
1012 if (state != STATE_DEAD) {
1013 if(state != STATE_STOPPED) {
1014 lose("gc_start_the_world: wrong thread state is %d\n",
1015 fixnum_value(state));
1017 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
1018 p->os_thread));
1019 set_thread_state(p, STATE_RUNNING);
1024 lock_ret = pthread_mutex_unlock(&all_threads_lock);
1025 gc_assert(lock_ret == 0);
1026 #ifdef LOCK_CREATE_THREAD
1027 lock_ret = pthread_mutex_unlock(&create_thread_lock);
1028 gc_assert(lock_ret == 0);
1029 #endif
1031 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
1034 #endif /* !LISP_FEATURE_SB_SAFEPOINT */
1035 #endif /* !LISP_FEATURE_SB_THREAD */
1038 thread_yield()
1040 #ifdef LISP_FEATURE_SB_THREAD
1041 return sched_yield();
1042 #else
1043 return 0;
1044 #endif
1048 wake_thread(os_thread_t os_thread)
1050 #if defined(LISP_FEATURE_WIN32)
1051 return kill_safely(os_thread, 1);
1052 #elif !defined(LISP_FEATURE_SB_THRUPTION)
1053 return kill_safely(os_thread, SIGPIPE);
1054 #else
1055 return wake_thread_posix(os_thread);
1056 #endif
1059 /* If the thread id given does not belong to a running thread (it has
1060 * exited or never even existed) pthread_kill _may_ fail with ESRCH,
1061 * but it is also allowed to just segfault, see
1062 * <http://udrepper.livejournal.com/16844.html>.
1064 * Relying on thread ids can easily backfire since ids are recycled
1065 * (NPTL recycles them extremely fast) so a signal can be sent to
1066 * another process if the one it was sent to exited.
1068 * For these reasons, we must make sure that the thread is still alive
1069 * when the pthread_kill is called and return if the thread is
1070 * exiting.
1072 * Note (DFL, 2011-06-22): At the time of writing, this function is only
1073 * used for INTERRUPT-THREAD, hence the wake_thread special-case for
1074 * Windows is OK. */
1076 kill_safely(os_thread_t os_thread, int signal)
1078 FSHOW_SIGNAL((stderr,"/kill_safely: %lu, %d\n", os_thread, signal));
1080 #ifdef LISP_FEATURE_SB_THREAD
1081 sigset_t oldset;
1082 struct thread *thread;
1083 /* Frequent special case: resignalling to self. The idea is
1084 * that leave_region safepoint will acknowledge the signal, so
1085 * there is no need to take locks, roll thread to safepoint
1086 * etc. */
1087 /* Kludge (on safepoint builds): At the moment, this isn't just
1088 * an optimization; rather it masks the fact that
1089 * gc_stop_the_world() grabs the all_threads mutex without
1090 * releasing it, and since we're not using recursive pthread
1091 * mutexes, the pthread_mutex_lock() around the all_threads loop
1092 * would go wrong. Why are we running interruptions while
1093 * stopping the world though? Test case is (:ASYNC-UNWIND
1094 * :SPECIALS), especially with s/10/100/ in both loops. */
1095 if (os_thread == pthread_self()) {
1096 pthread_kill(os_thread, signal);
1097 #ifdef LISP_FEATURE_WIN32
1098 check_pending_thruptions(NULL);
1099 #endif
1100 return 0;
1103 /* pthread_kill is not async signal safe and we don't want to be
1104 * interrupted while holding the lock. */
1105 block_deferrable_signals(0, &oldset);
1106 pthread_mutex_lock(&all_threads_lock);
1107 for (thread = all_threads; thread; thread = thread->next) {
1108 if (thread->os_thread == os_thread) {
1109 int status = pthread_kill(os_thread, signal);
1110 if (status)
1111 lose("kill_safely: pthread_kill failed with %d\n", status);
1112 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THRUPTION)
1113 wake_thread_win32(thread);
1114 #endif
1115 break;
1118 pthread_mutex_unlock(&all_threads_lock);
1119 thread_sigmask(SIG_SETMASK,&oldset,0);
1120 if (thread)
1121 return 0;
1122 else
1123 return -1;
1124 #elif defined(LISP_FEATURE_WIN32)
1125 return 0;
1126 #else
1127 int status;
1128 if (os_thread != 0)
1129 lose("kill_safely: who do you want to kill? %d?\n", os_thread);
1130 /* Dubious (as in don't know why it works) workaround for the
1131 * signal sometimes not being generated on darwin. */
1132 #ifdef LISP_FEATURE_DARWIN
1134 sigset_t oldset;
1135 sigprocmask(SIG_BLOCK, &deferrable_sigset, &oldset);
1136 status = raise(signal);
1137 sigprocmask(SIG_SETMASK,&oldset,0);
1139 #else
1140 status = raise(signal);
1141 #endif
1142 if (status == 0) {
1143 return 0;
1144 } else {
1145 lose("cannot raise signal %d, %d %s\n",
1146 signal, status, strerror(errno));
1148 #endif