Fix attach_thread to allocate a TLS index for *gc-inhibit* if needed
[sbcl.git] / src / runtime / thread.c
1 /*
2  * This software is part of the SBCL system. See the README file for
3  * more information.
4  *
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.
10  */
11
12 #include "sbcl.h"
13
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 "runtime.h"
21 #include <stddef.h>
22 #include <errno.h>
23 #include <sys/types.h>
24 #ifndef LISP_FEATURE_WIN32
25 #include <sys/wait.h>
26 #endif
27
28 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
29 #include <mach/mach.h>
30 #include <mach/mach_error.h>
31 #include <mach/mach_types.h>
32 #endif
33
34 #include "runtime.h"
35 #include "validate.h"           /* for BINDING_STACK_SIZE etc */
36 #include "thread.h"
37 #include "arch.h"
38 #include "target-arch-os.h"
39 #include "os.h"
40 #include "globals.h"
41 #include "dynbind.h"
42 #include "genesis/cons.h"
43 #include "genesis/fdefn.h"
44 #include "interr.h"             /* for lose() */
45 #include "alloc.h"
46 #include "gc-internal.h"
47 #include "cpputil.h"
48 #include "pseudo-atomic.h"
49 #include "interrupt.h"
50 #include "lispregs.h"
51
52 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD)
53 # define IMMEDIATE_POST_MORTEM
54 #endif
55
56 #if defined(LISP_FEATURE_DARWIN) && defined(LISP_FEATURE_SB_THREAD)
57 #define DELAY_THREAD_POST_MORTEM 5
58 #define LOCK_CREATE_THREAD
59 #endif
60
61 #ifdef LISP_FEATURE_FREEBSD
62 #define CREATE_CLEANUP_THREAD
63 #define LOCK_CREATE_THREAD
64 #endif
65
66 #ifdef LISP_FEATURE_SB_THREAD
67 struct thread_post_mortem {
68 #ifdef DELAY_THREAD_POST_MORTEM
69     struct thread_post_mortem *next;
70 #endif
71     os_thread_t os_thread;
72     pthread_attr_t *os_attr;
73     os_vm_address_t os_address;
74 };
75
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;
79 #endif
80 static struct thread_post_mortem * volatile pending_thread_post_mortem = 0;
81 #endif
82
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;
86
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;
91 #endif
92 #ifdef LISP_FEATURE_GCC_TLS
93 __thread struct thread *current_thread;
94 #endif
95 pthread_key_t lisp_thread = 0;
96 #endif
97
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))
102 # endif
103     ;
104 #endif
105
106 static void
107 link_thread(struct thread *th)
108 {
109     if (all_threads) all_threads->prev=th;
110     th->next=all_threads;
111     th->prev=0;
112     all_threads=th;
113 }
114
115 #ifdef LISP_FEATURE_SB_THREAD
116 static void
117 unlink_thread(struct thread *th)
118 {
119     if (th->prev)
120         th->prev->next = th->next;
121     else
122         all_threads = th->next;
123     if (th->next)
124         th->next->prev = th->prev;
125 }
126
127 #ifndef LISP_FEATURE_SB_SAFEPOINT
128 /* Only access thread state with blockables blocked. */
129 lispobj
130 thread_state(struct thread *thread)
131 {
132     lispobj state;
133     sigset_t old;
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);
139     return state;
140 }
141
142 void
143 set_thread_state(struct thread *thread, lispobj state)
144 {
145     int i, waitcount = 0;
146     sigset_t old;
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)");
156         }
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)");
163         }
164         thread->state = state;
165     }
166     os_sem_post(thread->state_sem, "set_thread_state");
167     thread_sigmask(SIG_SETMASK, &old, NULL);
168 }
169
170 void
171 wait_for_thread_state_change(struct thread *thread, lispobj state)
172 {
173     sigset_t old;
174     os_sem_t *wait_sem;
175     block_blockable_signals(NULL, &old);
176   start:
177     os_sem_wait(thread->state_sem, "wait_for_thread_state_change");
178     if (thread->state == state) {
179         switch (state) {
180         case STATE_RUNNING:
181             wait_sem = thread->state_not_running_sem;
182             thread->state_not_running_waitcount++;
183             break;
184         case STATE_STOPPED:
185             wait_sem = thread->state_not_stopped_sem;
186             thread->state_not_stopped_waitcount++;
187             break;
188         default:
189             lose("Invalid state in wait_for_thread_state_change: "OBJ_FMTX"\n", state);
190         }
191     } else {
192         wait_sem = NULL;
193     }
194     os_sem_post(thread->state_sem, "wait_for_thread_state_change");
195     if (wait_sem) {
196         os_sem_wait(wait_sem, "wait_for_thread_state_change");
197         goto start;
198     }
199     thread_sigmask(SIG_SETMASK, &old, NULL);
200 }
201 #endif /* sb-safepoint */
202 #endif /* sb-thread */
203
204 static int
205 initial_thread_trampoline(struct thread *th)
206 {
207     lispobj function;
208 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
209     lispobj *args = NULL;
210 #endif
211 #ifdef LISP_FEATURE_SB_THREAD
212     pthread_setspecific(lisp_thread, (void *)1);
213 #endif
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);
217 #endif
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;
221     link_thread(th);
222     th->os_thread=thread_self();
223 #ifndef LISP_FEATURE_WIN32
224     protect_control_stack_hard_guard_page(1, NULL);
225 #endif
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);
230 #endif
231     protect_binding_stack_guard_page(1, NULL);
232     protect_alien_stack_guard_page(1, NULL);
233
234 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
235     return call_into_lisp_first_time(function,args,0);
236 #else
237     return funcall0(function);
238 #endif
239 }
240
241 #ifdef LISP_FEATURE_SB_THREAD
242
243 # if defined(IMMEDIATE_POST_MORTEM)
244
245 /*
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.
248  */
249 static void
250 schedule_thread_post_mortem(struct thread *corpse)
251 {
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);
257 #else
258     os_invalidate(corpse->os_address, THREAD_STRUCT_SIZE);
259 #endif
260 }
261
262 # else
263
264 /* THREAD POST MORTEM CLEANUP
265  *
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. */
272
273 static struct thread_post_mortem *
274 plan_thread_post_mortem(struct thread *corpse)
275 {
276     if (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;
284 #endif
285         return post_mortem;
286     } else {
287         /* FIXME: When does this happen? */
288         return NULL;
289     }
290 }
291
292 static void
293 perform_thread_post_mortem(struct thread_post_mortem *post_mortem)
294 {
295 #ifdef CREATE_POST_MORTEM_THREAD
296     pthread_detach(pthread_self());
297 #endif
298     if (post_mortem) {
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);
303         free(post_mortem);
304     }
305 }
306
307 static void
308 schedule_thread_post_mortem(struct thread *corpse)
309 {
310     struct thread_post_mortem *post_mortem = NULL;
311     if (corpse) {
312         post_mortem = plan_thread_post_mortem(corpse);
313
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;
319             while (next->next) {
320                 next = next->next;
321             }
322             next->next = post_mortem;
323         } else {
324             pending_thread_post_mortem = post_mortem;
325         }
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;
332         } else {
333             pending_thread_post_mortem_count++;
334             post_mortem = NULL;
335         }
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));
341 #else
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);
346 #endif
347     }
348 }
349
350 # endif /* !IMMEDIATE_POST_MORTEM */
351
352 /* Note: scribble must be stack-allocated */
353 static void
354 init_new_thread(struct thread *th, init_thread_data *scribble, int guardp)
355 {
356     int lock_ret;
357
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");
362     }
363
364     th->os_thread=thread_self();
365     if (guardp)
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
372      * it is not). */
373 #ifdef LISP_FEATURE_SB_SAFEPOINT
374     *th->csp_around_foreign_call = (lispobj)scribble;
375 #endif
376     lock_ret = pthread_mutex_lock(&all_threads_lock);
377     gc_assert(lock_ret == 0);
378     link_thread(th);
379     lock_ret = pthread_mutex_unlock(&all_threads_lock);
380     gc_assert(lock_ret == 0);
381
382     /* Kludge: Changed the order of some steps between the safepoint/
383      * non-safepoint versions of this code.  Can we unify this more?
384      */
385 #ifdef LISP_FEATURE_SB_SAFEPOINT
386     gc_state_lock();
387     gc_state_wait(GC_NONE);
388     gc_state_unlock();
389     push_gcing_safety(&scribble->safety);
390 #endif
391 }
392
393 static void
394 undo_init_new_thread(struct thread *th, init_thread_data *scribble)
395 {
396     int lock_ret;
397
398     /* Kludge: Changed the order of some steps between the safepoint/
399      * non-safepoint versions of this code.  Can we unify this more?
400      */
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 #if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
405     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->sprof_alloc_region);
406 #endif
407     pop_gcing_safety(&scribble->safety);
408     lock_ret = pthread_mutex_lock(&all_threads_lock);
409     gc_assert(lock_ret == 0);
410     unlink_thread(th);
411     lock_ret = pthread_mutex_unlock(&all_threads_lock);
412     gc_assert(lock_ret == 0);
413 #else
414     /* Block GC */
415     block_blockable_signals(0, 0);
416     set_thread_state(th, STATE_DEAD);
417
418     /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
419      * thread, but since we are already dead it won't wait long. */
420     lock_ret = pthread_mutex_lock(&all_threads_lock);
421     gc_assert(lock_ret == 0);
422
423     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
424 #if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
425     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->sprof_alloc_region);
426 #endif
427     unlink_thread(th);
428     pthread_mutex_unlock(&all_threads_lock);
429     gc_assert(lock_ret == 0);
430 #endif
431
432     if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
433 #ifndef LISP_FEATURE_SB_SAFEPOINT
434     os_sem_destroy(th->state_sem);
435     os_sem_destroy(th->state_not_running_sem);
436     os_sem_destroy(th->state_not_stopped_sem);
437 #endif
438
439 #if defined(LISP_FEATURE_WIN32)
440     free((os_vm_address_t)th->interrupt_data);
441 #else
442     os_invalidate((os_vm_address_t)th->interrupt_data,
443                   (sizeof (struct interrupt_data)));
444 #endif
445
446 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
447     mach_lisp_thread_destroy(th);
448 #endif
449
450 #if defined(LISP_FEATURE_WIN32)
451     int i;
452     for (i = 0; i<
453              (int) (sizeof(th->private_events.events)/
454                     sizeof(th->private_events.events[0])); ++i) {
455       CloseHandle(th->private_events.events[i]);
456     }
457     TlsSetValue(OUR_TLS_INDEX,NULL);
458 #endif
459
460     /* Undo the association of the current pthread to its `struct thread',
461      * such that we can call arch_os_get_current_thread() later in this
462      * thread and cleanly get back NULL. */
463 #ifdef LISP_FEATURE_GCC_TLS
464     current_thread = NULL;
465 #else
466     pthread_setspecific(specials, NULL);
467 #endif
468
469     schedule_thread_post_mortem(th);
470 }
471
472 /* this is the first thing that runs in the child (which is why the
473  * silly calling convention).  Basically it calls the user's requested
474  * lisp function after doing arch_os_thread_init and whatever other
475  * bookkeeping needs to be done
476  */
477 int
478 new_thread_trampoline(struct thread *th)
479 {
480     int result;
481     init_thread_data scribble;
482
483     FSHOW((stderr,"/creating thread %lu\n", thread_self()));
484     check_deferrables_blocked_or_lose(0);
485 #ifndef LISP_FEATURE_SB_SAFEPOINT
486     check_gc_signals_unblocked_or_lose(0);
487 #endif
488
489     lispobj function = th->no_tls_value_marker;
490     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
491     init_new_thread(th, &scribble, 1);
492     result = funcall0(function);
493     undo_init_new_thread(th, &scribble);
494
495     FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
496     return result;
497 }
498
499 # ifdef LISP_FEATURE_SB_SAFEPOINT
500 static struct thread *create_thread_struct(lispobj);
501
502 void
503 attach_os_thread(init_thread_data *scribble)
504 {
505     os_thread_t os = pthread_self();
506     odxprint(misc, "attach_os_thread: attaching to %p", os);
507
508     struct thread *th = create_thread_struct(NIL);
509     block_deferrable_signals(0, &scribble->oldset);
510     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
511     /* We don't actually want a pthread_attr here, but rather than add
512      * `if's to the post-mostem, let's just keep that code happy by
513      * keeping it initialized: */
514     pthread_attr_init(th->os_attr);
515
516 #ifndef LISP_FEATURE_WIN32
517     /* On windows, arch_os_thread_init will take care of finding the
518      * stack. */
519     pthread_attr_t attr;
520     int pthread_getattr_np(pthread_t, pthread_attr_t *);
521     pthread_getattr_np(os, &attr);
522     void *stack_addr;
523     size_t stack_size;
524     pthread_attr_getstack(&attr, &stack_addr, &stack_size);
525     th->control_stack_start = stack_addr;
526     th->control_stack_end = (void *) (((uintptr_t) stack_addr) + stack_size);
527 #endif
528
529     init_new_thread(th, scribble, 0);
530
531     /* We will be calling into Lisp soon, and the functions being called
532      * recklessly ignore the comment in target-thread which says that we
533      * must be careful to not cause GC while initializing a new thread.
534      * Since we first need to create a fresh thread object, it's really
535      * tempting to just perform such unsafe allocation though.  So let's
536      * at least try to suppress GC before consing, and hope that it
537      * works: */
538     bind_variable(GC_INHIBIT, T, th);
539
540     uword_t stacksize
541         = (uword_t) th->control_stack_end - (uword_t) th->control_stack_start;
542     odxprint(misc, "attach_os_thread: attached %p as %p (0x%lx bytes stack)",
543              os, th, (long) stacksize);
544 }
545
546 void
547 detach_os_thread(init_thread_data *scribble)
548 {
549     struct thread *th = arch_os_get_current_thread();
550     odxprint(misc, "detach_os_thread: detaching");
551
552     undo_init_new_thread(th, scribble);
553
554     odxprint(misc, "deattach_os_thread: detached");
555     pthread_setspecific(lisp_thread, (void *)0);
556     thread_sigmask(SIG_SETMASK, &scribble->oldset, 0);
557 }
558 # endif /* safepoint */
559
560 #endif /* LISP_FEATURE_SB_THREAD */
561
562 static void
563 free_thread_struct(struct thread *th)
564 {
565 #if defined(LISP_FEATURE_WIN32)
566     if (th->interrupt_data) {
567         os_invalidate_free((os_vm_address_t) th->interrupt_data,
568                       (sizeof (struct interrupt_data)));
569     }
570     os_invalidate_free((os_vm_address_t) th->os_address,
571                   THREAD_STRUCT_SIZE);
572 #else
573     if (th->interrupt_data)
574         os_invalidate((os_vm_address_t) th->interrupt_data,
575                       (sizeof (struct interrupt_data)));
576     os_invalidate((os_vm_address_t) th->os_address,
577                   THREAD_STRUCT_SIZE);
578 #endif
579 }
580
581 #ifdef LISP_FEATURE_SB_THREAD
582 /* FIXME: should be MAX_INTERRUPTS -1 ? */
583 const unsigned int tls_index_start =
584   MAX_INTERRUPTS + sizeof(struct thread)/sizeof(lispobj);
585 #endif
586
587 /* this is called from any other thread to create the new one, and
588  * initialize all parts of it that can be initialized from another
589  * thread
590  */
591
592 static struct thread *
593 create_thread_struct(lispobj initial_function) {
594     union per_thread_data *per_thread;
595     struct thread *th=0;        /*  subdue gcc */
596     void *spaces=0;
597     void *aligned_spaces=0;
598 #if defined(LISP_FEATURE_SB_THREAD) || defined(LISP_FEATURE_WIN32)
599     unsigned int i;
600 #endif
601
602     /* May as well allocate all the spaces at once: it saves us from
603      * having to decide what to do if only some of the allocations
604      * succeed. SPACES must be appropriately aligned, since the GC
605      * expects the control stack to start at a page boundary -- and
606      * the OS may have even more rigorous requirements. We can't rely
607      * on the alignment passed from os_validate, since that might
608      * assume the current (e.g. 4k) pagesize, while we calculate with
609      * the biggest (e.g. 64k) pagesize allowed by the ABI. */
610     spaces=os_validate(0, THREAD_STRUCT_SIZE);
611     if(!spaces)
612         return NULL;
613     /* Aligning up is safe as THREAD_STRUCT_SIZE has
614      * THREAD_ALIGNMENT_BYTES padding. */
615     aligned_spaces = (void *)((((uword_t)(char *)spaces)
616                                + THREAD_ALIGNMENT_BYTES-1)
617                               &~(uword_t)(THREAD_ALIGNMENT_BYTES-1));
618     void* csp_page=
619         (aligned_spaces+
620          thread_control_stack_size+
621          BINDING_STACK_SIZE+
622          ALIEN_STACK_SIZE);
623     per_thread=(union per_thread_data *)
624         (csp_page + THREAD_CSP_PAGE_SIZE);
625     struct nonpointer_thread_data *nonpointer_data
626         = (void *) &per_thread->dynamic_values[TLS_SIZE];
627
628 #ifdef LISP_FEATURE_SB_THREAD
629     for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
630         per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
631     if (all_threads == 0) {
632         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
633             SetSymbolValue(FREE_TLS_INDEX,tls_index_start << WORD_SHIFT,0);
634             SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
635         }
636 #define STATIC_TLS_INIT(sym,field) \
637   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
638   (THREAD_SLOT_OFFSET_WORDS(field) << WORD_SHIFT)
639
640         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
641 #ifdef BINDING_STACK_POINTER
642         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
643 #endif
644         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
645         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
646 #ifdef ALIEN_STACK
647         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
648 #endif
649 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
650         STATIC_TLS_INIT(PSEUDO_ATOMIC_BITS,pseudo_atomic_bits);
651 #endif
652 #undef STATIC_TLS_INIT
653     }
654 #endif
655
656     th=&per_thread->thread;
657     th->os_address = spaces;
658     th->control_stack_start = aligned_spaces;
659     th->binding_stack_start=
660         (lispobj*)((void*)th->control_stack_start+thread_control_stack_size);
661     th->control_stack_end = th->binding_stack_start;
662     th->control_stack_guard_page_protected = T;
663     th->alien_stack_start=
664         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
665     set_binding_stack_pointer(th,th->binding_stack_start);
666     th->this=th;
667     th->os_thread=0;
668
669 #ifdef LISP_FEATURE_SB_SAFEPOINT
670 # ifdef LISP_FEATURE_WIN32
671     th->carried_base_pointer = 0;
672 # endif
673 # ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
674     th->pc_around_foreign_call = 0;
675 # endif
676     th->csp_around_foreign_call = csp_page;
677 #endif
678
679 #ifdef LISP_FEATURE_SB_THREAD
680     /* Contrary to the "allocate all the spaces at once" comment above,
681      * the os_attr is allocated separately.  We cannot put it into the
682      * nonpointer data, because it's used for post_mortem and freed
683      * separately */
684     th->os_attr=malloc(sizeof(pthread_attr_t));
685     th->nonpointer_data = nonpointer_data;
686 # ifndef LISP_FEATURE_SB_SAFEPOINT
687     th->state_sem=&nonpointer_data->state_sem;
688     th->state_not_running_sem=&nonpointer_data->state_not_running_sem;
689     th->state_not_stopped_sem=&nonpointer_data->state_not_stopped_sem;
690     os_sem_init(th->state_sem, 1);
691     os_sem_init(th->state_not_running_sem, 0);
692     os_sem_init(th->state_not_stopped_sem, 0);
693 # endif
694     th->state_not_running_waitcount = 0;
695     th->state_not_stopped_waitcount = 0;
696 #endif
697     th->state=STATE_RUNNING;
698 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
699     th->alien_stack_pointer=((void *)th->alien_stack_start
700                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
701 #else
702     th->alien_stack_pointer=((void *)th->alien_stack_start);
703 #endif
704 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64) || defined(LISP_FEATURE_SB_THREAD)
705     th->pseudo_atomic_bits=0;
706 #endif
707 #ifdef LISP_FEATURE_GENCGC
708     gc_set_region_empty(&th->alloc_region);
709 # if defined(LISP_FEATURE_SB_SAFEPOINT_STRICTLY) && !defined(LISP_FEATURE_WIN32)
710     gc_set_region_empty(&th->sprof_alloc_region);
711 # endif
712 #endif
713 #ifdef LISP_FEATURE_SB_THREAD
714     /* This parallels the same logic in globals.c for the
715      * single-threaded foreign_function_call_active, KLUDGE and
716      * all. */
717 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
718     th->foreign_function_call_active = 0;
719 #else
720     th->foreign_function_call_active = 1;
721 #endif
722 #endif
723
724 #ifndef LISP_FEATURE_SB_THREAD
725     /* the tls-points-into-struct-thread trick is only good for threaded
726      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
727      * appropriate values from struct thread here, and make sure that
728      * we use the appropriate SymbolValue macros to access any of the
729      * variable quantities from the C runtime.  It's not quite OAOOM,
730      * it just feels like it */
731     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
732     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
733     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
734 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
735     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
736     SetSymbolValue(PSEUDO_ATOMIC_BITS,(lispobj)th->pseudo_atomic_bits,th);
737 #endif
738 #endif
739     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
740     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
741     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
742     bind_variable(INTERRUPT_PENDING, NIL,th);
743     bind_variable(INTERRUPTS_ENABLED,T,th);
744     bind_variable(ALLOW_WITH_INTERRUPTS,T,th);
745     bind_variable(GC_PENDING,NIL,th);
746     bind_variable(ALLOC_SIGNAL,NIL,th);
747 #ifdef PINNED_OBJECTS
748     bind_variable(PINNED_OBJECTS,NIL,th);
749 #endif
750 #ifdef LISP_FEATURE_SB_THREAD
751     bind_variable(STOP_FOR_GC_PENDING,NIL,th);
752 #endif
753 #if defined(LISP_FEATURE_SB_SAFEPOINT)
754     bind_variable(GC_SAFE,NIL,th);
755     bind_variable(IN_SAFEPOINT,NIL,th);
756 #endif
757 #ifdef LISP_FEATURE_SB_THRUPTION
758     bind_variable(THRUPTION_PENDING,NIL,th);
759     bind_variable(RESTART_CLUSTERS,NIL,th);
760 #endif
761 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
762     access_control_stack_pointer(th)=th->control_stack_start;
763 #endif
764
765 #if defined(LISP_FEATURE_WIN32)
766     th->interrupt_data = (struct interrupt_data *)
767         calloc((sizeof (struct interrupt_data)),1);
768 #else
769     th->interrupt_data = (struct interrupt_data *)
770         os_validate(0,(sizeof (struct interrupt_data)));
771 #endif
772     if (!th->interrupt_data) {
773         free_thread_struct(th);
774         return 0;
775     }
776     th->interrupt_data->pending_handler = 0;
777     th->interrupt_data->gc_blocked_deferrables = 0;
778 #ifdef GENCGC_IS_PRECISE
779     th->interrupt_data->allocation_trap_context = 0;
780 #endif
781     th->no_tls_value_marker=initial_function;
782
783 #if defined(LISP_FEATURE_WIN32)
784     for (i = 0; i<sizeof(th->private_events.events)/
785            sizeof(th->private_events.events[0]); ++i) {
786       th->private_events.events[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
787     }
788     th->synchronous_io_handle_and_flag = 0;
789 #endif
790     th->stepping = NIL;
791     return th;
792 }
793
794 void create_initial_thread(lispobj initial_function) {
795     struct thread *th=create_thread_struct(initial_function);
796 #ifdef LISP_FEATURE_SB_THREAD
797     pthread_key_create(&lisp_thread, 0);
798 #endif
799     if(th) {
800         initial_thread_trampoline(th); /* no return */
801     } else lose("can't create initial thread\n");
802 }
803
804 #ifdef LISP_FEATURE_SB_THREAD
805
806 #ifndef __USE_XOPEN2K
807 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
808                                   size_t __stacksize);
809 #endif
810
811 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
812 {
813     /* The new thread inherits the restrictive signal mask set here,
814      * and enables signals again when it is set up properly. */
815     sigset_t oldset;
816     boolean r=1;
817     int retcode = 0, initcode;
818
819     FSHOW_SIGNAL((stderr,"/create_os_thread: creating new thread\n"));
820
821     /* Blocking deferrable signals is enough, no need to block
822      * SIG_STOP_FOR_GC because the child process is not linked onto
823      * all_threads until it's ready. */
824     block_deferrable_signals(0, &oldset);
825
826 #ifdef LOCK_CREATE_THREAD
827     retcode = pthread_mutex_lock(&create_thread_lock);
828     gc_assert(retcode == 0);
829     FSHOW_SIGNAL((stderr,"/create_os_thread: got lock\n"));
830 #endif
831
832     if((initcode = pthread_attr_init(th->os_attr)) ||
833        /* call_into_lisp_first_time switches the stack for the initial
834         * thread. For the others, we use this. */
835 #if defined(LISP_FEATURE_WIN32)
836        (pthread_attr_setstacksize(th->os_attr, thread_control_stack_size)) ||
837 #else
838        (pthread_attr_setstack(th->os_attr,th->control_stack_start,
839                               thread_control_stack_size)) ||
840 #endif
841        (retcode = pthread_create
842         (kid_tid,th->os_attr,(void *(*)(void *))new_thread_trampoline,th))) {
843         FSHOW_SIGNAL((stderr, "init = %d\n", initcode));
844         FSHOW_SIGNAL((stderr, "pthread_create returned %d, errno %d\n",
845                       retcode, errno));
846         if(retcode < 0) {
847             perror("create_os_thread");
848         }
849         r=0;
850     }
851
852 #ifdef LOCK_CREATE_THREAD
853     retcode = pthread_mutex_unlock(&create_thread_lock);
854     gc_assert(retcode == 0);
855     FSHOW_SIGNAL((stderr,"/create_os_thread: released lock\n"));
856 #endif
857     thread_sigmask(SIG_SETMASK,&oldset,0);
858     return r;
859 }
860
861 os_thread_t create_thread(lispobj initial_function) {
862     struct thread *th, *thread = arch_os_get_current_thread();
863     os_thread_t kid_tid = 0;
864
865     /* Must defend against async unwinds. */
866     if (SymbolValue(INTERRUPTS_ENABLED, thread) != NIL)
867         lose("create_thread is not safe when interrupts are enabled.\n");
868
869     /* Assuming that a fresh thread struct has no lisp objects in it,
870      * linking it to all_threads can be left to the thread itself
871      * without fear of gc lossage. initial_function violates this
872      * assumption and must stay pinned until the child starts up. */
873     th = create_thread_struct(initial_function);
874     if (th && !create_os_thread(th,&kid_tid)) {
875         free_thread_struct(th);
876         kid_tid = 0;
877     }
878     return kid_tid;
879 }
880
881 /* stopping the world is a two-stage process.  From this thread we signal
882  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
883  * the usual pseudo-atomic checks (we don't want to stop a thread while
884  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
885  */
886 /*
887  * (With SB-SAFEPOINT, see the definitions in safepoint.c instead.)
888  */
889 #ifndef LISP_FEATURE_SB_SAFEPOINT
890
891 /* To avoid deadlocks when gc stops the world all clients of each
892  * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
893  * holding the lock, but they must agree on which. */
894 void gc_stop_the_world()
895 {
896     struct thread *p,*th=arch_os_get_current_thread();
897     int status, lock_ret;
898 #ifdef LOCK_CREATE_THREAD
899     /* KLUDGE: Stopping the thread during pthread_create() causes deadlock
900      * on FreeBSD. */
901     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on create_thread_lock\n"));
902     lock_ret = pthread_mutex_lock(&create_thread_lock);
903     gc_assert(lock_ret == 0);
904     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got create_thread_lock\n"));
905 #endif
906     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock\n"));
907     /* keep threads from starting while the world is stopped. */
908     lock_ret = pthread_mutex_lock(&all_threads_lock);      \
909     gc_assert(lock_ret == 0);
910
911     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock\n"));
912     /* stop all other threads by sending them SIG_STOP_FOR_GC */
913     for(p=all_threads; p; p=p->next) {
914         gc_assert(p->os_thread != 0);
915         FSHOW_SIGNAL((stderr,"/gc_stop_the_world: thread=%lu, state=%x\n",
916                       p->os_thread, thread_state(p)));
917         if((p!=th) && ((thread_state(p)==STATE_RUNNING))) {
918             FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending thread %lu\n",
919                           p->os_thread));
920             /* We already hold all_thread_lock, P can become DEAD but
921              * cannot exit, ergo it's safe to use pthread_kill. */
922             status=pthread_kill(p->os_thread,SIG_STOP_FOR_GC);
923             if (status==ESRCH) {
924                 /* This thread has exited. */
925                 gc_assert(thread_state(p)==STATE_DEAD);
926             } else if (status) {
927                 lose("cannot send suspend thread=%lu: %d, %s\n",
928                      p->os_thread,status,strerror(status));
929             }
930         }
931     }
932     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
933     for(p=all_threads;p;p=p->next) {
934         if (p!=th) {
935             FSHOW_SIGNAL
936                 ((stderr,
937                   "/gc_stop_the_world: waiting for thread=%lu: state=%x\n",
938                   p->os_thread, thread_state(p)));
939             wait_for_thread_state_change(p, STATE_RUNNING);
940             if (p->state == STATE_RUNNING)
941                 lose("/gc_stop_the_world: unexpected state");
942         }
943     }
944     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
945 }
946
947 void gc_start_the_world()
948 {
949     struct thread *p,*th=arch_os_get_current_thread();
950     int lock_ret;
951     /* if a resumed thread creates a new thread before we're done with
952      * this loop, the new thread will get consed on the front of
953      * all_threads, but it won't have been stopped so won't need
954      * restarting */
955     FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
956     for(p=all_threads;p;p=p->next) {
957         gc_assert(p->os_thread!=0);
958         if (p!=th) {
959             lispobj state = thread_state(p);
960             if (state != STATE_DEAD) {
961                 if(state != STATE_STOPPED) {
962                     lose("gc_start_the_world: wrong thread state is %d\n",
963                          fixnum_value(state));
964                 }
965                 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
966                               p->os_thread));
967                 set_thread_state(p, STATE_RUNNING);
968             }
969         }
970     }
971
972     lock_ret = pthread_mutex_unlock(&all_threads_lock);
973     gc_assert(lock_ret == 0);
974 #ifdef LOCK_CREATE_THREAD
975     lock_ret = pthread_mutex_unlock(&create_thread_lock);
976     gc_assert(lock_ret == 0);
977 #endif
978
979     FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
980 }
981
982 #endif /* !LISP_FEATURE_SB_SAFEPOINT */
983 #endif /* !LISP_FEATURE_SB_THREAD */
984
985 int
986 thread_yield()
987 {
988 #ifdef LISP_FEATURE_SB_THREAD
989     return sched_yield();
990 #else
991     return 0;
992 #endif
993 }
994
995 int
996 wake_thread(os_thread_t os_thread)
997 {
998 #if defined(LISP_FEATURE_WIN32)
999     return kill_safely(os_thread, 1);
1000 #elif !defined(LISP_FEATURE_SB_THRUPTION)
1001     return kill_safely(os_thread, SIGPIPE);
1002 #else
1003     return wake_thread_posix(os_thread);
1004 #endif
1005 }
1006
1007 /* If the thread id given does not belong to a running thread (it has
1008  * exited or never even existed) pthread_kill _may_ fail with ESRCH,
1009  * but it is also allowed to just segfault, see
1010  * <http://udrepper.livejournal.com/16844.html>.
1011  *
1012  * Relying on thread ids can easily backfire since ids are recycled
1013  * (NPTL recycles them extremely fast) so a signal can be sent to
1014  * another process if the one it was sent to exited.
1015  *
1016  * For these reasons, we must make sure that the thread is still alive
1017  * when the pthread_kill is called and return if the thread is
1018  * exiting.
1019  *
1020  * Note (DFL, 2011-06-22): At the time of writing, this function is only
1021  * used for INTERRUPT-THREAD, hence the wake_thread special-case for
1022  * Windows is OK. */
1023 int
1024 kill_safely(os_thread_t os_thread, int signal)
1025 {
1026     FSHOW_SIGNAL((stderr,"/kill_safely: %lu, %d\n", os_thread, signal));
1027     {
1028 #ifdef LISP_FEATURE_SB_THREAD
1029         sigset_t oldset;
1030         struct thread *thread;
1031         /* Frequent special case: resignalling to self.  The idea is
1032          * that leave_region safepoint will acknowledge the signal, so
1033          * there is no need to take locks, roll thread to safepoint
1034          * etc. */
1035         /* Kludge (on safepoint builds): At the moment, this isn't just
1036          * an optimization; rather it masks the fact that
1037          * gc_stop_the_world() grabs the all_threads mutex without
1038          * releasing it, and since we're not using recursive pthread
1039          * mutexes, the pthread_mutex_lock() around the all_threads loop
1040          * would go wrong.  Why are we running interruptions while
1041          * stopping the world though?  Test case is (:ASYNC-UNWIND
1042          * :SPECIALS), especially with s/10/100/ in both loops. */
1043         if (os_thread == pthread_self()) {
1044             pthread_kill(os_thread, signal);
1045 #ifdef LISP_FEATURE_WIN32
1046             check_pending_thruptions(NULL);
1047 #endif
1048             return 0;
1049         }
1050
1051         /* pthread_kill is not async signal safe and we don't want to be
1052          * interrupted while holding the lock. */
1053         block_deferrable_signals(0, &oldset);
1054         pthread_mutex_lock(&all_threads_lock);
1055         for (thread = all_threads; thread; thread = thread->next) {
1056             if (thread->os_thread == os_thread) {
1057                 int status = pthread_kill(os_thread, signal);
1058                 if (status)
1059                     lose("kill_safely: pthread_kill failed with %d\n", status);
1060 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THRUPTION)
1061                 wake_thread_win32(thread);
1062 #endif
1063                 break;
1064             }
1065         }
1066         pthread_mutex_unlock(&all_threads_lock);
1067         thread_sigmask(SIG_SETMASK,&oldset,0);
1068         if (thread)
1069             return 0;
1070         else
1071             return -1;
1072 #elif defined(LISP_FEATURE_WIN32)
1073         return 0;
1074 #else
1075         int status;
1076         if (os_thread != 0)
1077             lose("kill_safely: who do you want to kill? %d?\n", os_thread);
1078         /* Dubious (as in don't know why it works) workaround for the
1079          * signal sometimes not being generated on darwin. */
1080 #ifdef LISP_FEATURE_DARWIN
1081         {
1082             sigset_t oldset;
1083             sigprocmask(SIG_BLOCK, &deferrable_sigset, &oldset);
1084             status = raise(signal);
1085             sigprocmask(SIG_SETMASK,&oldset,0);
1086         }
1087 #else
1088         status = raise(signal);
1089 #endif
1090         if (status == 0) {
1091             return 0;
1092         } else {
1093             lose("cannot raise signal %d, %d %s\n",
1094                  signal, status, strerror(errno));
1095         }
1096 #endif
1097     }
1098 }