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