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