a30ff4ffb2681778610a10b6318cb01426a06df7
[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 #endif
101
102 static void
103 link_thread(struct thread *th)
104 {
105     if (all_threads) all_threads->prev=th;
106     th->next=all_threads;
107     th->prev=0;
108     all_threads=th;
109 }
110
111 #ifdef LISP_FEATURE_SB_THREAD
112 static void
113 unlink_thread(struct thread *th)
114 {
115     if (th->prev)
116         th->prev->next = th->next;
117     else
118         all_threads = th->next;
119     if (th->next)
120         th->next->prev = th->prev;
121 }
122
123 #ifndef LISP_FEATURE_SB_SAFEPOINT
124 /* Only access thread state with blockables blocked. */
125 lispobj
126 thread_state(struct thread *thread)
127 {
128     lispobj state;
129     sigset_t old;
130     block_blockable_signals(NULL, &old);
131     os_sem_wait(thread->state_sem, "thread_state");
132     state = thread->state;
133     os_sem_post(thread->state_sem, "thread_state");
134     thread_sigmask(SIG_SETMASK, &old, NULL);
135     return state;
136 }
137
138 void
139 set_thread_state(struct thread *thread, lispobj state)
140 {
141     int i, waitcount = 0;
142     sigset_t old;
143     block_blockable_signals(NULL, &old);
144     os_sem_wait(thread->state_sem, "set_thread_state");
145     if (thread->state != state) {
146         if ((STATE_STOPPED==state) ||
147             (STATE_DEAD==state)) {
148             waitcount = thread->state_not_running_waitcount;
149             thread->state_not_running_waitcount = 0;
150             for (i=0; i<waitcount; i++)
151                 os_sem_post(thread->state_not_running_sem, "set_thread_state (not running)");
152         }
153         if ((STATE_RUNNING==state) ||
154             (STATE_DEAD==state)) {
155             waitcount = thread->state_not_stopped_waitcount;
156             thread->state_not_stopped_waitcount = 0;
157             for (i=0; i<waitcount; i++)
158                 os_sem_post(thread->state_not_stopped_sem, "set_thread_state (not stopped)");
159         }
160         thread->state = state;
161     }
162     os_sem_post(thread->state_sem, "set_thread_state");
163     thread_sigmask(SIG_SETMASK, &old, NULL);
164 }
165
166 void
167 wait_for_thread_state_change(struct thread *thread, lispobj state)
168 {
169     sigset_t old;
170     os_sem_t *wait_sem;
171     block_blockable_signals(NULL, &old);
172   start:
173     os_sem_wait(thread->state_sem, "wait_for_thread_state_change");
174     if (thread->state == state) {
175         switch (state) {
176         case STATE_RUNNING:
177             wait_sem = thread->state_not_running_sem;
178             thread->state_not_running_waitcount++;
179             break;
180         case STATE_STOPPED:
181             wait_sem = thread->state_not_stopped_sem;
182             thread->state_not_stopped_waitcount++;
183             break;
184         default:
185             lose("Invalid state in wait_for_thread_state_change: "OBJ_FMTX"\n", state);
186         }
187     } else {
188         wait_sem = NULL;
189     }
190     os_sem_post(thread->state_sem, "wait_for_thread_state_change");
191     if (wait_sem) {
192         os_sem_wait(wait_sem, "wait_for_thread_state_change");
193         goto start;
194     }
195     thread_sigmask(SIG_SETMASK, &old, NULL);
196 }
197 #endif /* sb-safepoint */
198 #endif /* sb-thread */
199
200 static int
201 initial_thread_trampoline(struct thread *th)
202 {
203     lispobj function;
204 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
205     lispobj *args = NULL;
206 #endif
207 #ifdef LISP_FEATURE_SB_THREAD
208     pthread_setspecific(lisp_thread, (void *)1);
209 #endif
210 #if defined(THREADS_USING_GCSIGNAL) && defined(LISP_FEATURE_PPC)
211     /* SIG_STOP_FOR_GC defaults to blocked on PPC? */
212     unblock_gc_signals(0,0);
213 #endif
214     function = th->no_tls_value_marker;
215     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
216     if(arch_os_thread_init(th)==0) return 1;
217     link_thread(th);
218     th->os_thread=thread_self();
219 #ifndef LISP_FEATURE_WIN32
220     protect_control_stack_hard_guard_page(1, NULL);
221 #endif
222     protect_binding_stack_hard_guard_page(1, NULL);
223     protect_alien_stack_hard_guard_page(1, NULL);
224 #ifndef LISP_FEATURE_WIN32
225     protect_control_stack_guard_page(1, NULL);
226 #endif
227     protect_binding_stack_guard_page(1, NULL);
228     protect_alien_stack_guard_page(1, NULL);
229
230 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
231     return call_into_lisp_first_time(function,args,0);
232 #else
233     return funcall0(function);
234 #endif
235 }
236
237 #ifdef LISP_FEATURE_SB_THREAD
238
239 # if defined(IMMEDIATE_POST_MORTEM)
240
241 /*
242  * If this feature is set, we are running on a stack managed by the OS,
243  * and no fancy delays are required for anything.  Just do it.
244  */
245 static void
246 schedule_thread_post_mortem(struct thread *corpse)
247 {
248     pthread_detach(pthread_self());
249     gc_assert(!pthread_attr_destroy(corpse->os_attr));
250     free(corpse->os_attr);
251 #if defined(LISP_FEATURE_WIN32)
252     os_invalidate_free(corpse->os_address, THREAD_STRUCT_SIZE);
253 #else
254     os_invalidate(corpse->os_address, THREAD_STRUCT_SIZE);
255 #endif
256 }
257
258 # else
259
260 /* THREAD POST MORTEM CLEANUP
261  *
262  * Memory allocated for the thread stacks cannot be reclaimed while
263  * the thread is still alive, so we need a mechanism for post mortem
264  * cleanups. FIXME: We actually have three, for historical reasons as
265  * the saying goes. Do we really need three? Nikodemus guesses that
266  * not anymore, now that we properly call pthread_attr_destroy before
267  * freeing the stack. */
268
269 static struct thread_post_mortem *
270 plan_thread_post_mortem(struct thread *corpse)
271 {
272     if (corpse) {
273         struct thread_post_mortem *post_mortem = malloc(sizeof(struct thread_post_mortem));
274         gc_assert(post_mortem);
275         post_mortem->os_thread = corpse->os_thread;
276         post_mortem->os_attr = corpse->os_attr;
277         post_mortem->os_address = corpse->os_address;
278 #ifdef DELAY_THREAD_POST_MORTEM
279         post_mortem->next = NULL;
280 #endif
281         return post_mortem;
282     } else {
283         /* FIXME: When does this happen? */
284         return NULL;
285     }
286 }
287
288 static void
289 perform_thread_post_mortem(struct thread_post_mortem *post_mortem)
290 {
291 #ifdef CREATE_POST_MORTEM_THREAD
292     pthread_detach(pthread_self());
293 #endif
294     if (post_mortem) {
295         gc_assert(!pthread_join(post_mortem->os_thread, NULL));
296         gc_assert(!pthread_attr_destroy(post_mortem->os_attr));
297         free(post_mortem->os_attr);
298         os_invalidate(post_mortem->os_address, THREAD_STRUCT_SIZE);
299         free(post_mortem);
300     }
301 }
302
303 static void
304 schedule_thread_post_mortem(struct thread *corpse)
305 {
306     struct thread_post_mortem *post_mortem = NULL;
307     if (corpse) {
308         post_mortem = plan_thread_post_mortem(corpse);
309
310 #ifdef DELAY_THREAD_POST_MORTEM
311         pthread_mutex_lock(&thread_post_mortem_lock);
312         /* First stick the new post mortem to the end of the queue. */
313         if (pending_thread_post_mortem) {
314             struct thread_post_mortem *next = pending_thread_post_mortem;
315             while (next->next) {
316                 next = next->next;
317             }
318             next->next = post_mortem;
319         } else {
320             pending_thread_post_mortem = post_mortem;
321         }
322         /* Then, if there are enough things in the queue, clean up one
323          * from the head -- or increment the count, and null out the
324          * post_mortem we have. */
325         if (pending_thread_post_mortem_count > DELAY_THREAD_POST_MORTEM) {
326             post_mortem = pending_thread_post_mortem;
327             pending_thread_post_mortem = post_mortem->next;
328         } else {
329             pending_thread_post_mortem_count++;
330             post_mortem = NULL;
331         }
332         pthread_mutex_unlock(&thread_post_mortem_lock);
333         /* Finally run, the cleanup, if any. */
334         perform_thread_post_mortem(post_mortem);
335 #elif defined(CREATE_POST_MORTEM_THREAD)
336         gc_assert(!pthread_create(&thread, NULL, perform_thread_post_mortem, post_mortem));
337 #else
338         post_mortem = (struct thread_post_mortem *)
339             swap_lispobjs((lispobj *)(void *)&pending_thread_post_mortem,
340                           (lispobj)post_mortem);
341         perform_thread_post_mortem(post_mortem);
342 #endif
343     }
344 }
345
346 # endif /* !IMMEDIATE_POST_MORTEM */
347
348 /* this is the first thing that runs in the child (which is why the
349  * silly calling convention).  Basically it calls the user's requested
350  * lisp function after doing arch_os_thread_init and whatever other
351  * bookkeeping needs to be done
352  */
353 int
354 new_thread_trampoline(struct thread *th)
355 {
356     lispobj function;
357     int result, lock_ret;
358
359     FSHOW((stderr,"/creating thread %lu\n", thread_self()));
360     check_deferrables_blocked_or_lose(0);
361 #ifndef LISP_FEATURE_SB_SAFEPOINT
362     check_gc_signals_unblocked_or_lose(0);
363 #endif
364     pthread_setspecific(lisp_thread, (void *)1);
365     function = th->no_tls_value_marker;
366     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
367     if(arch_os_thread_init(th)==0) {
368         /* FIXME: handle error */
369         lose("arch_os_thread_init failed\n");
370     }
371
372     th->os_thread=thread_self();
373     protect_control_stack_guard_page(1, NULL);
374     protect_binding_stack_guard_page(1, NULL);
375     protect_alien_stack_guard_page(1, NULL);
376     /* Since GC can only know about this thread from the all_threads
377      * list and we're just adding this thread to it, there is no
378      * danger of deadlocking even with SIG_STOP_FOR_GC blocked (which
379      * it is not). */
380 #ifdef LISP_FEATURE_SB_SAFEPOINT
381     *th->csp_around_foreign_call = (lispobj)&function;
382 #endif
383     lock_ret = pthread_mutex_lock(&all_threads_lock);
384     gc_assert(lock_ret == 0);
385     link_thread(th);
386     lock_ret = pthread_mutex_unlock(&all_threads_lock);
387     gc_assert(lock_ret == 0);
388
389     /* Kludge: Changed the order of some steps between the safepoint/
390      * non-safepoint versions of this code.  Can we unify this more?
391      */
392 #ifdef LISP_FEATURE_SB_SAFEPOINT
393     gc_state_lock();
394     gc_state_wait(GC_NONE);
395     gc_state_unlock();
396     WITH_GC_AT_SAFEPOINTS_ONLY() {
397         result = funcall0(function);
398         block_blockable_signals(0, 0);
399         gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
400     }
401     lock_ret = pthread_mutex_lock(&all_threads_lock);
402     gc_assert(lock_ret == 0);
403     unlink_thread(th);
404     lock_ret = pthread_mutex_unlock(&all_threads_lock);
405     gc_assert(lock_ret == 0);
406 #else
407     result = funcall0(function);
408
409     /* Block GC */
410     block_blockable_signals(0, 0);
411     set_thread_state(th, STATE_DEAD);
412
413     /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
414      * thread, but since we are already dead it won't wait long. */
415     lock_ret = pthread_mutex_lock(&all_threads_lock);
416     gc_assert(lock_ret == 0);
417
418     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
419     unlink_thread(th);
420     pthread_mutex_unlock(&all_threads_lock);
421     gc_assert(lock_ret == 0);
422 #endif
423
424     if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
425 #ifndef LISP_FEATURE_SB_SAFEPOINT
426     os_sem_destroy(th->state_sem);
427     os_sem_destroy(th->state_not_running_sem);
428     os_sem_destroy(th->state_not_stopped_sem);
429 #endif
430
431 #if defined(LISP_FEATURE_WIN32)
432     free((os_vm_address_t)th->interrupt_data);
433 #else
434     os_invalidate((os_vm_address_t)th->interrupt_data,
435                   (sizeof (struct interrupt_data)));
436 #endif
437
438 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
439     mach_lisp_thread_destroy(th);
440 #endif
441
442 #if defined(LISP_FEATURE_WIN32)
443     int i;
444     for (i = 0; i<
445              (int) (sizeof(th->private_events.events)/
446                     sizeof(th->private_events.events[0])); ++i) {
447       CloseHandle(th->private_events.events[i]);
448     }
449     TlsSetValue(OUR_TLS_INDEX,NULL);
450 #endif
451
452     schedule_thread_post_mortem(th);
453     FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
454     return result;
455 }
456
457 #endif /* LISP_FEATURE_SB_THREAD */
458
459 static void
460 free_thread_struct(struct thread *th)
461 {
462 #if defined(LISP_FEATURE_WIN32)
463     if (th->interrupt_data) {
464         os_invalidate_free((os_vm_address_t) th->interrupt_data,
465                       (sizeof (struct interrupt_data)));
466     }
467     os_invalidate_free((os_vm_address_t) th->os_address,
468                   THREAD_STRUCT_SIZE);
469 #else
470     if (th->interrupt_data)
471         os_invalidate((os_vm_address_t) th->interrupt_data,
472                       (sizeof (struct interrupt_data)));
473     os_invalidate((os_vm_address_t) th->os_address,
474                   THREAD_STRUCT_SIZE);
475 #endif
476 }
477
478 #ifdef LISP_FEATURE_SB_THREAD
479 /* FIXME: should be MAX_INTERRUPTS -1 ? */
480 const unsigned int tls_index_start =
481   MAX_INTERRUPTS + sizeof(struct thread)/sizeof(lispobj);
482 #endif
483
484 /* this is called from any other thread to create the new one, and
485  * initialize all parts of it that can be initialized from another
486  * thread
487  */
488
489 static struct thread *
490 create_thread_struct(lispobj initial_function) {
491     union per_thread_data *per_thread;
492     struct thread *th=0;        /*  subdue gcc */
493     void *spaces=0;
494     void *aligned_spaces=0;
495 #if defined(LISP_FEATURE_SB_THREAD) || defined(LISP_FEATURE_WIN32)
496     unsigned int i;
497 #endif
498
499     /* May as well allocate all the spaces at once: it saves us from
500      * having to decide what to do if only some of the allocations
501      * succeed. SPACES must be appropriately aligned, since the GC
502      * expects the control stack to start at a page boundary -- and
503      * the OS may have even more rigorous requirements. We can't rely
504      * on the alignment passed from os_validate, since that might
505      * assume the current (e.g. 4k) pagesize, while we calculate with
506      * the biggest (e.g. 64k) pagesize allowed by the ABI. */
507     spaces=os_validate(0, THREAD_STRUCT_SIZE);
508     if(!spaces)
509         return NULL;
510     /* Aligning up is safe as THREAD_STRUCT_SIZE has
511      * THREAD_ALIGNMENT_BYTES padding. */
512     aligned_spaces = (void *)((((unsigned long)(char *)spaces)
513                                + THREAD_ALIGNMENT_BYTES-1)
514                               &~(unsigned long)(THREAD_ALIGNMENT_BYTES-1));
515     void* csp_page=
516         (aligned_spaces+
517          thread_control_stack_size+
518          BINDING_STACK_SIZE+
519          ALIEN_STACK_SIZE);
520     per_thread=(union per_thread_data *)
521         (csp_page + THREAD_CSP_PAGE_SIZE);
522     struct nonpointer_thread_data *nonpointer_data
523         = (void *) &per_thread->dynamic_values[TLS_SIZE];
524
525 #ifdef LISP_FEATURE_SB_THREAD
526     for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
527         per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
528     if (all_threads == 0) {
529         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
530             SetSymbolValue(FREE_TLS_INDEX,tls_index_start << WORD_SHIFT,0);
531             SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
532         }
533 #define STATIC_TLS_INIT(sym,field) \
534   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
535   (THREAD_SLOT_OFFSET_WORDS(field) << WORD_SHIFT)
536
537         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
538 #ifdef BINDING_STACK_POINTER
539         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
540 #endif
541         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
542         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
543 #ifdef ALIEN_STACK
544         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
545 #endif
546 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
547         STATIC_TLS_INIT(PSEUDO_ATOMIC_BITS,pseudo_atomic_bits);
548 #endif
549 #undef STATIC_TLS_INIT
550     }
551 #endif
552
553     th=&per_thread->thread;
554     th->os_address = spaces;
555     th->control_stack_start = aligned_spaces;
556     th->binding_stack_start=
557         (lispobj*)((void*)th->control_stack_start+thread_control_stack_size);
558     th->control_stack_end = th->binding_stack_start;
559     th->control_stack_guard_page_protected = T;
560     th->alien_stack_start=
561         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
562     set_binding_stack_pointer(th,th->binding_stack_start);
563     th->this=th;
564     th->os_thread=0;
565
566 #ifdef LISP_FEATURE_SB_SAFEPOINT
567     th->pc_around_foreign_call = 0;
568     th->csp_around_foreign_call = csp_page;
569 #endif
570
571 #ifdef LISP_FEATURE_SB_THREAD
572     /* Contrary to the "allocate all the spaces at once" comment above,
573      * the os_attr is allocated separately.  We cannot put it into the
574      * nonpointer data, because it's used for post_mortem and freed
575      * separately */
576     th->os_attr=malloc(sizeof(pthread_attr_t));
577     th->nonpointer_data = nonpointer_data;
578 # ifndef LISP_FEATURE_SB_SAFEPOINT
579     th->state_sem=&nonpointer_data->state_sem;
580     th->state_not_running_sem=&nonpointer_data->state_not_running_sem;
581     th->state_not_stopped_sem=&nonpointer_data->state_not_stopped_sem;
582     os_sem_init(th->state_sem, 1);
583     os_sem_init(th->state_not_running_sem, 0);
584     os_sem_init(th->state_not_stopped_sem, 0);
585 # endif
586     th->state_not_running_waitcount = 0;
587     th->state_not_stopped_waitcount = 0;
588 #endif
589     th->state=STATE_RUNNING;
590 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
591     th->alien_stack_pointer=((void *)th->alien_stack_start
592                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
593 #else
594     th->alien_stack_pointer=((void *)th->alien_stack_start);
595 #endif
596 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64) || defined(LISP_FEATURE_SB_THREAD)
597     th->pseudo_atomic_bits=0;
598 #endif
599 #ifdef LISP_FEATURE_GENCGC
600     gc_set_region_empty(&th->alloc_region);
601 #endif
602 #ifdef LISP_FEATURE_SB_THREAD
603     /* This parallels the same logic in globals.c for the
604      * single-threaded foreign_function_call_active, KLUDGE and
605      * all. */
606 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
607     th->foreign_function_call_active = 0;
608 #else
609     th->foreign_function_call_active = 1;
610 #endif
611 #endif
612
613 #ifndef LISP_FEATURE_SB_THREAD
614     /* the tls-points-into-struct-thread trick is only good for threaded
615      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
616      * appropriate values from struct thread here, and make sure that
617      * we use the appropriate SymbolValue macros to access any of the
618      * variable quantities from the C runtime.  It's not quite OAOOM,
619      * it just feels like it */
620     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
621     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
622     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
623 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
624     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
625     SetSymbolValue(PSEUDO_ATOMIC_BITS,(lispobj)th->pseudo_atomic_bits,th);
626 #endif
627 #endif
628     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
629     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
630     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
631     bind_variable(INTERRUPT_PENDING, NIL,th);
632     bind_variable(INTERRUPTS_ENABLED,T,th);
633     bind_variable(ALLOW_WITH_INTERRUPTS,T,th);
634     bind_variable(GC_PENDING,NIL,th);
635     bind_variable(ALLOC_SIGNAL,NIL,th);
636 #ifdef PINNED_OBJECTS
637     bind_variable(PINNED_OBJECTS,NIL,th);
638 #endif
639 #ifdef LISP_FEATURE_SB_THREAD
640     bind_variable(STOP_FOR_GC_PENDING,NIL,th);
641 #endif
642 #if defined(LISP_FEATURE_SB_SAFEPOINT)
643     bind_variable(GC_SAFE,NIL,th);
644     bind_variable(IN_SAFEPOINT,NIL,th);
645 #endif
646 #ifdef LISP_FEATURE_SB_THRUPTION
647     bind_variable(THRUPTION_PENDING,NIL,th);
648     bind_variable(RESTART_CLUSTERS,NIL,th);
649 #endif
650 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
651     access_control_stack_pointer(th)=th->control_stack_start;
652 #endif
653
654 #if defined(LISP_FEATURE_WIN32)
655     th->interrupt_data = (struct interrupt_data *)
656         calloc((sizeof (struct interrupt_data)),1);
657 #else
658     th->interrupt_data = (struct interrupt_data *)
659         os_validate(0,(sizeof (struct interrupt_data)));
660 #endif
661     if (!th->interrupt_data) {
662         free_thread_struct(th);
663         return 0;
664     }
665     th->interrupt_data->pending_handler = 0;
666     th->interrupt_data->gc_blocked_deferrables = 0;
667 #ifdef GENCGC_IS_PRECISE
668     th->interrupt_data->allocation_trap_context = 0;
669 #endif
670     th->no_tls_value_marker=initial_function;
671
672 #if defined(LISP_FEATURE_WIN32)
673     for (i = 0; i<sizeof(th->private_events.events)/
674            sizeof(th->private_events.events[0]); ++i) {
675       th->private_events.events[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
676     }
677     th->synchronous_io_handle_and_flag = 0;
678 #endif
679     th->stepping = NIL;
680     return th;
681 }
682
683 void create_initial_thread(lispobj initial_function) {
684     struct thread *th=create_thread_struct(initial_function);
685 #ifdef LISP_FEATURE_SB_THREAD
686     pthread_key_create(&lisp_thread, 0);
687 #endif
688     if(th) {
689         initial_thread_trampoline(th); /* no return */
690     } else lose("can't create initial thread\n");
691 }
692
693 #ifdef LISP_FEATURE_SB_THREAD
694
695 #ifndef __USE_XOPEN2K
696 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
697                                   size_t __stacksize);
698 #endif
699
700 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
701 {
702     /* The new thread inherits the restrictive signal mask set here,
703      * and enables signals again when it is set up properly. */
704     sigset_t oldset;
705     boolean r=1;
706     int retcode = 0, initcode;
707
708     FSHOW_SIGNAL((stderr,"/create_os_thread: creating new thread\n"));
709
710     /* Blocking deferrable signals is enough, no need to block
711      * SIG_STOP_FOR_GC because the child process is not linked onto
712      * all_threads until it's ready. */
713     block_deferrable_signals(0, &oldset);
714
715 #ifdef LOCK_CREATE_THREAD
716     retcode = pthread_mutex_lock(&create_thread_lock);
717     gc_assert(retcode == 0);
718     FSHOW_SIGNAL((stderr,"/create_os_thread: got lock\n"));
719 #endif
720
721     if((initcode = pthread_attr_init(th->os_attr)) ||
722        /* call_into_lisp_first_time switches the stack for the initial
723         * thread. For the others, we use this. */
724 #if defined(LISP_FEATURE_WIN32)
725        (pthread_attr_setstacksize(th->os_attr, thread_control_stack_size)) ||
726 #else
727        (pthread_attr_setstack(th->os_attr,th->control_stack_start,
728                               thread_control_stack_size)) ||
729 #endif
730        (retcode = pthread_create
731         (kid_tid,th->os_attr,(void *(*)(void *))new_thread_trampoline,th))) {
732         FSHOW_SIGNAL((stderr, "init = %d\n", initcode));
733         FSHOW_SIGNAL((stderr, "pthread_create returned %d, errno %d\n",
734                       retcode, errno));
735         if(retcode < 0) {
736             perror("create_os_thread");
737         }
738         r=0;
739     }
740
741 #ifdef LOCK_CREATE_THREAD
742     retcode = pthread_mutex_unlock(&create_thread_lock);
743     gc_assert(retcode == 0);
744     FSHOW_SIGNAL((stderr,"/create_os_thread: released lock\n"));
745 #endif
746     thread_sigmask(SIG_SETMASK,&oldset,0);
747     return r;
748 }
749
750 os_thread_t create_thread(lispobj initial_function) {
751     struct thread *th, *thread = arch_os_get_current_thread();
752     os_thread_t kid_tid = 0;
753
754     /* Must defend against async unwinds. */
755     if (SymbolValue(INTERRUPTS_ENABLED, thread) != NIL)
756         lose("create_thread is not safe when interrupts are enabled.\n");
757
758     /* Assuming that a fresh thread struct has no lisp objects in it,
759      * linking it to all_threads can be left to the thread itself
760      * without fear of gc lossage. initial_function violates this
761      * assumption and must stay pinned until the child starts up. */
762     th = create_thread_struct(initial_function);
763     if (th && !create_os_thread(th,&kid_tid)) {
764         free_thread_struct(th);
765         kid_tid = 0;
766     }
767     return kid_tid;
768 }
769
770 /* stopping the world is a two-stage process.  From this thread we signal
771  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
772  * the usual pseudo-atomic checks (we don't want to stop a thread while
773  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
774  */
775 /*
776  * (With SB-SAFEPOINT, see the definitions in safepoint.c instead.)
777  */
778 #ifndef LISP_FEATURE_SB_SAFEPOINT
779
780 /* To avoid deadlocks when gc stops the world all clients of each
781  * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
782  * holding the lock, but they must agree on which. */
783 void gc_stop_the_world()
784 {
785     struct thread *p,*th=arch_os_get_current_thread();
786     int status, lock_ret;
787 #ifdef LOCK_CREATE_THREAD
788     /* KLUDGE: Stopping the thread during pthread_create() causes deadlock
789      * on FreeBSD. */
790     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on create_thread_lock\n"));
791     lock_ret = pthread_mutex_lock(&create_thread_lock);
792     gc_assert(lock_ret == 0);
793     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got create_thread_lock\n"));
794 #endif
795     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock\n"));
796     /* keep threads from starting while the world is stopped. */
797     lock_ret = pthread_mutex_lock(&all_threads_lock);      \
798     gc_assert(lock_ret == 0);
799
800     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock\n"));
801     /* stop all other threads by sending them SIG_STOP_FOR_GC */
802     for(p=all_threads; p; p=p->next) {
803         gc_assert(p->os_thread != 0);
804         FSHOW_SIGNAL((stderr,"/gc_stop_the_world: thread=%lu, state=%x\n",
805                       p->os_thread, thread_state(p)));
806         if((p!=th) && ((thread_state(p)==STATE_RUNNING))) {
807             FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending thread %lu\n",
808                           p->os_thread));
809             /* We already hold all_thread_lock, P can become DEAD but
810              * cannot exit, ergo it's safe to use pthread_kill. */
811             status=pthread_kill(p->os_thread,SIG_STOP_FOR_GC);
812             if (status==ESRCH) {
813                 /* This thread has exited. */
814                 gc_assert(thread_state(p)==STATE_DEAD);
815             } else if (status) {
816                 lose("cannot send suspend thread=%lu: %d, %s\n",
817                      p->os_thread,status,strerror(status));
818             }
819         }
820     }
821     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
822     for(p=all_threads;p;p=p->next) {
823         if (p!=th) {
824             FSHOW_SIGNAL
825                 ((stderr,
826                   "/gc_stop_the_world: waiting for thread=%lu: state=%x\n",
827                   p->os_thread, thread_state(p)));
828             wait_for_thread_state_change(p, STATE_RUNNING);
829             if (p->state == STATE_RUNNING)
830                 lose("/gc_stop_the_world: unexpected state");
831         }
832     }
833     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
834 }
835
836 void gc_start_the_world()
837 {
838     struct thread *p,*th=arch_os_get_current_thread();
839     int lock_ret;
840     /* if a resumed thread creates a new thread before we're done with
841      * this loop, the new thread will get consed on the front of
842      * all_threads, but it won't have been stopped so won't need
843      * restarting */
844     FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
845     for(p=all_threads;p;p=p->next) {
846         gc_assert(p->os_thread!=0);
847         if (p!=th) {
848             lispobj state = thread_state(p);
849             if (state != STATE_DEAD) {
850                 if(state != STATE_STOPPED) {
851                     lose("gc_start_the_world: wrong thread state is %d\n",
852                          fixnum_value(state));
853                 }
854                 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
855                               p->os_thread));
856                 set_thread_state(p, STATE_RUNNING);
857             }
858         }
859     }
860
861     lock_ret = pthread_mutex_unlock(&all_threads_lock);
862     gc_assert(lock_ret == 0);
863 #ifdef LOCK_CREATE_THREAD
864     lock_ret = pthread_mutex_unlock(&create_thread_lock);
865     gc_assert(lock_ret == 0);
866 #endif
867
868     FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
869 }
870
871 #endif /* !LISP_FEATURE_SB_SAFEPOINT */
872 #endif /* !LISP_FEATURE_SB_THREAD */
873
874 int
875 thread_yield()
876 {
877 #ifdef LISP_FEATURE_SB_THREAD
878     return sched_yield();
879 #else
880     return 0;
881 #endif
882 }
883
884 int
885 wake_thread(os_thread_t os_thread)
886 {
887 #if defined(LISP_FEATURE_WIN32)
888     return kill_safely(os_thread, 1);
889 #elif !defined(LISP_FEATURE_SB_THRUPTION)
890     return kill_safely(os_thread, SIGPIPE);
891 #else
892     return wake_thread_posix(os_thread);
893 #endif
894 }
895
896 /* If the thread id given does not belong to a running thread (it has
897  * exited or never even existed) pthread_kill _may_ fail with ESRCH,
898  * but it is also allowed to just segfault, see
899  * <http://udrepper.livejournal.com/16844.html>.
900  *
901  * Relying on thread ids can easily backfire since ids are recycled
902  * (NPTL recycles them extremely fast) so a signal can be sent to
903  * another process if the one it was sent to exited.
904  *
905  * For these reasons, we must make sure that the thread is still alive
906  * when the pthread_kill is called and return if the thread is
907  * exiting.
908  *
909  * Note (DFL, 2011-06-22): At the time of writing, this function is only
910  * used for INTERRUPT-THREAD, hence the wake_thread special-case for
911  * Windows is OK. */
912 int
913 kill_safely(os_thread_t os_thread, int signal)
914 {
915     FSHOW_SIGNAL((stderr,"/kill_safely: %lu, %d\n", os_thread, signal));
916     {
917 #ifdef LISP_FEATURE_SB_THREAD
918         sigset_t oldset;
919         struct thread *thread;
920         /* Frequent special case: resignalling to self.  The idea is
921          * that leave_region safepoint will acknowledge the signal, so
922          * there is no need to take locks, roll thread to safepoint
923          * etc. */
924         /* Kludge (on safepoint builds): At the moment, this isn't just
925          * an optimization; rather it masks the fact that
926          * gc_stop_the_world() grabs the all_threads mutex without
927          * releasing it, and since we're not using recursive pthread
928          * mutexes, the pthread_mutex_lock() around the all_threads loop
929          * would go wrong.  Why are we running interruptions while
930          * stopping the world though?  Test case is (:ASYNC-UNWIND
931          * :SPECIALS), especially with s/10/100/ in both loops. */
932         if (os_thread == pthread_self()) {
933             pthread_kill(os_thread, signal);
934 #ifdef LISP_FEATURE_WIN32
935             check_pending_thruptions(NULL);
936 #endif
937             return 0;
938         }
939
940         /* pthread_kill is not async signal safe and we don't want to be
941          * interrupted while holding the lock. */
942         block_deferrable_signals(0, &oldset);
943         pthread_mutex_lock(&all_threads_lock);
944         for (thread = all_threads; thread; thread = thread->next) {
945             if (thread->os_thread == os_thread) {
946                 int status = pthread_kill(os_thread, signal);
947                 if (status)
948                     lose("kill_safely: pthread_kill failed with %d\n", status);
949 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THRUPTION)
950                 wake_thread_win32(thread);
951 #endif
952                 break;
953             }
954         }
955         pthread_mutex_unlock(&all_threads_lock);
956         thread_sigmask(SIG_SETMASK,&oldset,0);
957         if (thread)
958             return 0;
959         else
960             return -1;
961 #elif defined(LISP_FEATURE_WIN32)
962         return 0;
963 #else
964         int status;
965         if (os_thread != 0)
966             lose("kill_safely: who do you want to kill? %d?\n", os_thread);
967         /* Dubious (as in don't know why it works) workaround for the
968          * signal sometimes not being generated on darwin. */
969 #ifdef LISP_FEATURE_DARWIN
970         {
971             sigset_t oldset;
972             sigprocmask(SIG_BLOCK, &deferrable_sigset, &oldset);
973             status = raise(signal);
974             sigprocmask(SIG_SETMASK,&oldset,0);
975         }
976 #else
977         status = raise(signal);
978 #endif
979         if (status == 0) {
980             return 0;
981         } else {
982             lose("cannot raise signal %d, %d %s\n",
983                  signal, status, strerror(errno));
984         }
985 #endif
986     }
987 }