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