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