e529c7d79c44b441b021f8ad7e6ea07858535acd
[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 #include "runtime.h"
29 #include "validate.h"           /* for CONTROL_STACK_SIZE etc */
30 #include "alloc.h"
31 #include "thread.h"
32 #include "arch.h"
33 #include "target-arch-os.h"
34 #include "os.h"
35 #include "globals.h"
36 #include "dynbind.h"
37 #include "genesis/cons.h"
38 #include "genesis/fdefn.h"
39 #include "interr.h"             /* for lose() */
40 #include "gc-internal.h"
41
42 #ifdef LISP_FEATURE_WIN32
43 /*
44  * Win32 doesn't have SIGSTKSZ, and we're not switching stacks anyway,
45  * so define it arbitrarily
46  */
47 #define SIGSTKSZ 1024
48 #endif
49
50 #if defined(LISP_FEATURE_DARWIN) && defined(LISP_FEATURE_SB_THREAD)
51 #define QUEUE_FREEABLE_THREAD_STACKS
52 #endif
53
54 #ifdef LISP_FEATURE_FREEBSD
55 #define CREATE_CLEANUP_THREAD
56 #define LOCK_CREATE_THREAD
57 #endif
58
59 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
60
61 struct freeable_stack {
62 #ifdef QUEUE_FREEABLE_THREAD_STACKS
63     struct freeable_stack *next;
64 #endif
65     os_thread_t os_thread;
66     os_vm_address_t stack;
67 };
68
69
70 #ifdef QUEUE_FREEABLE_THREAD_STACKS
71 static struct freeable_stack * volatile freeable_stack_queue = 0;
72 static int freeable_stack_count = 0;
73 pthread_mutex_t freeable_stack_lock = PTHREAD_MUTEX_INITIALIZER;
74 #else
75 static struct freeable_stack * volatile freeable_stack = 0;
76 #endif
77
78 int dynamic_values_bytes=4096*sizeof(lispobj);  /* same for all threads */
79 struct thread * volatile all_threads;
80 extern struct interrupt_data * global_interrupt_data;
81
82 #ifdef LISP_FEATURE_SB_THREAD
83 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
84 #ifdef LOCK_CREATE_THREAD
85 static pthread_mutex_t create_thread_lock = PTHREAD_MUTEX_INITIALIZER;
86 #endif
87 #endif
88
89 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
90 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs);
91 #endif
92
93 static void
94 link_thread(struct thread *th)
95 {
96     if (all_threads) all_threads->prev=th;
97     th->next=all_threads;
98     th->prev=0;
99     all_threads=th;
100 }
101
102 #ifdef LISP_FEATURE_SB_THREAD
103 static void
104 unlink_thread(struct thread *th)
105 {
106     if (th->prev)
107         th->prev->next = th->next;
108     else
109         all_threads = th->next;
110     if (th->next)
111         th->next->prev = th->prev;
112 }
113 #endif
114
115 static int
116 initial_thread_trampoline(struct thread *th)
117 {
118     lispobj function;
119 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
120     lispobj *args = NULL;
121 #endif
122     function = th->no_tls_value_marker;
123     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
124     if(arch_os_thread_init(th)==0) return 1;
125     link_thread(th);
126     th->os_thread=thread_self();
127 #ifndef LISP_FEATURE_WIN32
128     protect_control_stack_guard_page(1);
129 #endif
130
131 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
132     return call_into_lisp_first_time(function,args,0);
133 #else
134     return funcall0(function);
135 #endif
136 }
137
138 #define THREAD_STRUCT_SIZE (THREAD_CONTROL_STACK_SIZE + BINDING_STACK_SIZE + \
139                             ALIEN_STACK_SIZE + dynamic_values_bytes + \
140                             32 * SIGSTKSZ)
141
142 #ifdef LISP_FEATURE_SB_THREAD
143
144 #ifdef QUEUE_FREEABLE_THREAD_STACKS
145
146 queue_freeable_thread_stack(struct thread *thread_to_be_cleaned_up)
147 {
148      if (thread_to_be_cleaned_up) {
149         pthread_mutex_lock(&freeable_stack_lock);
150         if (freeable_stack_queue) {
151             struct freeable_stack *new_freeable_stack = 0, *next;
152             next = freeable_stack_queue;
153             while (next->next) {
154                 next = next->next;
155             }
156             new_freeable_stack = (struct freeable_stack *)
157                 os_validate(0, sizeof(struct freeable_stack));
158             new_freeable_stack->next = NULL;
159             new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
160             new_freeable_stack->stack = (os_vm_address_t)
161                 thread_to_be_cleaned_up->control_stack_start;
162             next->next = new_freeable_stack;
163             freeable_stack_count++;
164         } else {
165             struct freeable_stack *new_freeable_stack = 0;
166             new_freeable_stack = (struct freeable_stack *)
167                 os_validate(0, sizeof(struct freeable_stack));
168             new_freeable_stack->next = NULL;
169             new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
170             new_freeable_stack->stack = (os_vm_address_t)
171                 thread_to_be_cleaned_up->control_stack_start;
172             freeable_stack_queue = new_freeable_stack;
173             freeable_stack_count++;
174         }
175         pthread_mutex_unlock(&freeable_stack_lock);
176     }
177 }
178
179 #define FREEABLE_STACK_QUEUE_SIZE 4
180
181 static void
182 free_freeable_stacks() {
183     if (freeable_stack_queue && (freeable_stack_count > FREEABLE_STACK_QUEUE_SIZE)) {
184         struct freeable_stack* old;
185         pthread_mutex_lock(&freeable_stack_lock);
186         old = freeable_stack_queue;
187         freeable_stack_queue = old->next;
188         freeable_stack_count--;
189         gc_assert(pthread_join(old->os_thread, NULL) == 0);
190         FSHOW((stderr, "freeing thread %x stack\n", old->os_thread));
191         os_invalidate(old->stack, THREAD_STRUCT_SIZE);
192         os_invalidate((os_vm_address_t)old, sizeof(struct freeable_stack));
193         pthread_mutex_unlock(&freeable_stack_lock);
194     }
195 }
196
197 #elif defined(CREATE_CLEANUP_THREAD)
198 static void *
199 cleanup_thread(void *arg)
200 {
201     struct freeable_stack *freeable = arg;
202     pthread_t self = pthread_self();
203
204     FSHOW((stderr, "/cleaner thread(%p): joining %p\n",
205            self, freeable->os_thread));
206     gc_assert(pthread_join(freeable->os_thread, NULL) == 0);
207     FSHOW((stderr, "/cleaner thread(%p): free stack %p\n",
208            self, freeable->stack));
209     os_invalidate(freeable->stack, THREAD_STRUCT_SIZE);
210     free(freeable);
211
212     pthread_detach(self);
213
214     return NULL;
215 }
216
217 static void
218 create_cleanup_thread(struct thread *thread_to_be_cleaned_up)
219 {
220     pthread_t thread;
221     int result;
222
223     if (thread_to_be_cleaned_up) {
224         struct freeable_stack *freeable =
225             malloc(sizeof(struct freeable_stack));
226         gc_assert(freeable != NULL);
227         freeable->os_thread = thread_to_be_cleaned_up->os_thread;
228         freeable->stack =
229             (os_vm_address_t) thread_to_be_cleaned_up->control_stack_start;
230         result = pthread_create(&thread, NULL, cleanup_thread, freeable);
231         gc_assert(result == 0);
232         sched_yield();
233     }
234 }
235
236 #else
237 static void
238 free_thread_stack_later(struct thread *thread_to_be_cleaned_up)
239 {
240     struct freeable_stack *new_freeable_stack = 0;
241     if (thread_to_be_cleaned_up) {
242         new_freeable_stack = (struct freeable_stack *)
243             os_validate(0, sizeof(struct freeable_stack));
244         new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
245         new_freeable_stack->stack = (os_vm_address_t)
246             thread_to_be_cleaned_up->control_stack_start;
247     }
248     new_freeable_stack = (struct freeable_stack *)
249         swap_lispobjs((lispobj *)(void *)&freeable_stack,
250                       (lispobj)new_freeable_stack);
251     if (new_freeable_stack) {
252         FSHOW((stderr,"/reaping %p\n", (void*) new_freeable_stack->os_thread));
253         /* Under NPTL pthread_join really waits until the thread
254          * exists and the stack can be safely freed. This is sadly not
255          * mandated by the pthread spec. */
256         gc_assert(pthread_join(new_freeable_stack->os_thread, NULL) == 0);
257         os_invalidate(new_freeable_stack->stack, THREAD_STRUCT_SIZE);
258         os_invalidate((os_vm_address_t) new_freeable_stack,
259                       sizeof(struct freeable_stack));
260     }
261 }
262 #endif
263
264 /* this is the first thing that runs in the child (which is why the
265  * silly calling convention).  Basically it calls the user's requested
266  * lisp function after doing arch_os_thread_init and whatever other
267  * bookkeeping needs to be done
268  */
269 int
270 new_thread_trampoline(struct thread *th)
271 {
272     lispobj function;
273     int result, lock_ret;
274
275     FSHOW((stderr,"/creating thread %lu\n", thread_self()));
276     function = th->no_tls_value_marker;
277     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
278     if(arch_os_thread_init(th)==0) {
279         /* FIXME: handle error */
280         lose("arch_os_thread_init failed\n");
281     }
282
283     th->os_thread=thread_self();
284     protect_control_stack_guard_page(1);
285     /* Since GC can only know about this thread from the all_threads
286      * list and we're just adding this thread to it there is no danger
287      * of deadlocking even with SIG_STOP_FOR_GC blocked (which it is
288      * not). */
289     lock_ret = pthread_mutex_lock(&all_threads_lock);
290     gc_assert(lock_ret == 0);
291     link_thread(th);
292     lock_ret = pthread_mutex_unlock(&all_threads_lock);
293     gc_assert(lock_ret == 0);
294
295     result = funcall0(function);
296
297     /* Block GC */
298     block_blockable_signals();
299     th->state=STATE_DEAD;
300
301     /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
302      * thread, but since we are already dead it won't wait long. */
303     lock_ret = pthread_mutex_lock(&all_threads_lock);
304     gc_assert(lock_ret == 0);
305
306     gc_alloc_update_page_tables(0, &th->alloc_region);
307     unlink_thread(th);
308     pthread_mutex_unlock(&all_threads_lock);
309     gc_assert(lock_ret == 0);
310
311     if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
312     os_invalidate((os_vm_address_t)th->interrupt_data,
313                   (sizeof (struct interrupt_data)));
314
315 #ifdef QUEUE_FREEABLE_THREAD_STACKS
316     queue_freeable_thread_stack(th);
317 #elif defined(CREATE_CLEANUP_THREAD)
318     create_cleanup_thread(th);
319 #else
320     free_thread_stack_later(th);
321 #endif
322
323     FSHOW((stderr,"/exiting thread %p\n", thread_self()));
324     return result;
325 }
326
327 #endif /* LISP_FEATURE_SB_THREAD */
328
329 static void
330 free_thread_struct(struct thread *th)
331 {
332     if (th->interrupt_data)
333         os_invalidate((os_vm_address_t) th->interrupt_data,
334                       (sizeof (struct interrupt_data)));
335     os_invalidate((os_vm_address_t) th->control_stack_start,
336                   THREAD_STRUCT_SIZE);
337 }
338
339 /* this is called from any other thread to create the new one, and
340  * initialize all parts of it that can be initialized from another
341  * thread
342  */
343
344 static struct thread *
345 create_thread_struct(lispobj initial_function) {
346     union per_thread_data *per_thread;
347     struct thread *th=0;        /*  subdue gcc */
348     void *spaces=0;
349 #ifdef LISP_FEATURE_SB_THREAD
350     int i;
351 #endif
352
353 #ifdef CREATE_CLEANUP_THREAD
354     /* Give a chance for cleanup threads to run. */
355     sched_yield();
356 #endif
357     /* may as well allocate all the spaces at once: it saves us from
358      * having to decide what to do if only some of the allocations
359      * succeed */
360     spaces=os_validate(0, THREAD_STRUCT_SIZE);
361     if(!spaces)
362          return NULL;
363     per_thread=(union per_thread_data *)
364         (spaces+
365          THREAD_CONTROL_STACK_SIZE+
366          BINDING_STACK_SIZE+
367          ALIEN_STACK_SIZE);
368
369 #ifdef LISP_FEATURE_SB_THREAD
370     for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
371         per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
372     if (all_threads == 0) {
373         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
374             SetSymbolValue
375                 (FREE_TLS_INDEX,
376                  /* FIXME: should be MAX_INTERRUPTS -1 ? */
377                  make_fixnum(MAX_INTERRUPTS+
378                              sizeof(struct thread)/sizeof(lispobj)),
379                  0);
380             SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
381         }
382 #define STATIC_TLS_INIT(sym,field) \
383   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
384   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
385
386         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
387         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
388         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
389         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
390         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
391 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
392         STATIC_TLS_INIT(PSEUDO_ATOMIC_BITS,pseudo_atomic_bits);
393 #endif
394 #undef STATIC_TLS_INIT
395     }
396 #endif
397
398     th=&per_thread->thread;
399     th->control_stack_start = spaces;
400     th->binding_stack_start=
401         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
402     th->control_stack_end = th->binding_stack_start;
403     th->alien_stack_start=
404         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
405     th->binding_stack_pointer=th->binding_stack_start;
406     th->this=th;
407     th->os_thread=0;
408     th->state=STATE_RUNNING;
409 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
410     th->alien_stack_pointer=((void *)th->alien_stack_start
411                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
412 #else
413     th->alien_stack_pointer=((void *)th->alien_stack_start);
414 #endif
415 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
416     th->pseudo_atomic_bits=0;
417 #endif
418 #ifdef LISP_FEATURE_GENCGC
419     gc_set_region_empty(&th->alloc_region);
420 #endif
421
422 #ifndef LISP_FEATURE_SB_THREAD
423     /* the tls-points-into-struct-thread trick is only good for threaded
424      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
425      * appropriate values from struct thread here, and make sure that
426      * we use the appropriate SymbolValue macros to access any of the
427      * variable quantities from the C runtime.  It's not quite OAOOM,
428      * it just feels like it */
429     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
430     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
431     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
432 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
433     SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
434     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
435     SetSymbolValue(PSEUDO_ATOMIC_BITS,(lispobj)th->pseudo_atomic_bits,th);
436 #else
437     current_binding_stack_pointer=th->binding_stack_pointer;
438     current_control_stack_pointer=th->control_stack_start;
439 #endif
440 #endif
441     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
442     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
443     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
444     bind_variable(INTERRUPT_PENDING, NIL,th);
445     bind_variable(INTERRUPTS_ENABLED,T,th);
446     bind_variable(GC_PENDING,NIL,th);
447 #ifdef LISP_FEATURE_SB_THREAD
448     bind_variable(STOP_FOR_GC_PENDING,NIL,th);
449 #endif
450
451     th->interrupt_data = (struct interrupt_data *)
452         os_validate(0,(sizeof (struct interrupt_data)));
453     if (!th->interrupt_data) {
454         free_thread_struct(th);
455         return 0;
456     }
457     th->interrupt_data->pending_handler = 0;
458     th->no_tls_value_marker=initial_function;
459
460     th->stepping = NIL;
461     return th;
462 }
463
464 void create_initial_thread(lispobj initial_function) {
465     struct thread *th=create_thread_struct(initial_function);
466     if(th) {
467         initial_thread_trampoline(th); /* no return */
468     } else lose("can't create initial thread\n");
469 }
470
471 #ifdef LISP_FEATURE_SB_THREAD
472
473 #ifndef __USE_XOPEN2K
474 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
475                                   size_t __stacksize);
476 #endif
477
478 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
479 {
480     /* The new thread inherits the restrictive signal mask set here,
481      * and enables signals again when it is set up properly. */
482     pthread_attr_t attr;
483     sigset_t newset,oldset;
484     boolean r=1;
485     int retcode, initcode, sizecode, addrcode;
486
487     FSHOW_SIGNAL((stderr,"/create_os_thread: creating new thread\n"));
488
489 #ifdef LOCK_CREATE_THREAD
490     retcode = pthread_mutex_lock(&create_thread_lock);
491     gc_assert(retcode == 0);
492     FSHOW_SIGNAL((stderr,"/create_os_thread: got lock\n"));
493 #endif
494     sigemptyset(&newset);
495     /* Blocking deferrable signals is enough, no need to block
496      * SIG_STOP_FOR_GC because the child process is not linked onto
497      * all_threads until it's ready. */
498     sigaddset_deferrable(&newset);
499     thread_sigmask(SIG_BLOCK, &newset, &oldset);
500
501 #if defined(LISP_FEATURE_DARWIN)
502 #define CONTROL_STACK_ADJUST 8192 /* darwin wants page-aligned stacks */
503 #else
504 #define CONTROL_STACK_ADJUST 16
505 #endif
506
507     if((initcode = pthread_attr_init(&attr)) ||
508        /* FIXME: why do we even have this in the first place? */
509        (pthread_attr_setstack(&attr,th->control_stack_start,
510                               THREAD_CONTROL_STACK_SIZE-CONTROL_STACK_ADJUST)) ||
511 #undef CONTROL_STACK_ADJUST
512        (retcode = pthread_create
513         (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th))) {
514         FSHOW_SIGNAL((stderr, "init, size, addr = %d, %d, %d\n", initcode, sizecode, addrcode));
515         FSHOW_SIGNAL((stderr, printf("pthread_create returned %d, errno %d\n", retcode, errno)));
516         FSHOW_SIGNAL((stderr, "wanted stack size %d, min stack size %d\n",
517                       THREAD_CONTROL_STACK_SIZE-16, PTHREAD_STACK_MIN));
518         if(retcode < 0) {
519             perror("create_os_thread");
520         }
521         r=0;
522     }
523 #ifdef QUEUE_FREEABLE_THREAD_STACKS
524     free_freeable_stacks();
525 #endif
526     thread_sigmask(SIG_SETMASK,&oldset,0);
527 #ifdef LOCK_CREATE_THREAD
528     retcode = pthread_mutex_unlock(&create_thread_lock);
529     gc_assert(retcode == 0);
530     FSHOW_SIGNAL((stderr,"/create_os_thread: released lock\n"));
531 #endif
532     return r;
533 }
534
535 os_thread_t create_thread(lispobj initial_function) {
536     struct thread *th;
537     os_thread_t kid_tid;
538
539     /* Assuming that a fresh thread struct has no lisp objects in it,
540      * linking it to all_threads can be left to the thread itself
541      * without fear of gc lossage. initial_function violates this
542      * assumption and must stay pinned until the child starts up. */
543     th = create_thread_struct(initial_function);
544     if(th==0) return 0;
545
546     if (create_os_thread(th,&kid_tid)) {
547         return kid_tid;
548     } else {
549         free_thread_struct(th);
550         return 0;
551     }
552 }
553
554 /* Send the signo to os_thread, retry if the rt signal queue is
555  * full. */
556 int
557 kill_thread_safely(os_thread_t os_thread, int signo)
558 {
559     int r;
560     /* The man page does not mention EAGAIN as a valid return value
561      * for either pthread_kill or kill. But that's theory, this is
562      * practice. By waiting here we assume that the delivery of this
563      * signal is not necessary for the delivery of the signals in the
564      * queue. In other words, we _assume_ there are no deadlocks. */
565     while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
566         /* wait a bit then try again in the hope of the rt signal
567          * queue not being full */
568         FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
569         /* FIXME: some kind of backoff (random, exponential) would be
570          * nice. */
571         sleep(1);
572     }
573     return r;
574 }
575
576 int signal_interrupt_thread(os_thread_t os_thread)
577 {
578     int status = kill_thread_safely(os_thread, SIG_INTERRUPT_THREAD);
579     if (status == 0) {
580         return 0;
581     } else if (status == ESRCH) {
582         return -1;
583     } else {
584         lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s\n",
585              os_thread, status, strerror(status));
586     }
587 }
588
589 /* stopping the world is a two-stage process.  From this thread we signal
590  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
591  * the usual pseudo-atomic checks (we don't want to stop a thread while
592  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
593  */
594
595 /* To avoid deadlocks when gc stops the world all clients of each
596  * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
597  * holding the lock, but they must agree on which. */
598 void gc_stop_the_world()
599 {
600     struct thread *p,*th=arch_os_get_current_thread();
601     int status, lock_ret;
602 #ifdef LOCK_CREATE_THREAD
603     /* KLUDGE: Stopping the thread during pthread_create() causes deadlock
604      * on FreeBSD. */
605     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on create_thread_lock, thread=%lu\n",
606                   th->os_thread));
607     lock_ret = pthread_mutex_lock(&create_thread_lock);
608     gc_assert(lock_ret == 0);
609     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got create_thread_lock, thread=%lu\n",
610                   th->os_thread));
611 #endif
612     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
613                   th->os_thread));
614     /* keep threads from starting while the world is stopped. */
615     lock_ret = pthread_mutex_lock(&all_threads_lock);      \
616     gc_assert(lock_ret == 0);
617
618     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
619                   th->os_thread));
620     /* stop all other threads by sending them SIG_STOP_FOR_GC */
621     for(p=all_threads; p; p=p->next) {
622         gc_assert(p->os_thread != 0);
623         FSHOW_SIGNAL((stderr,"/gc_stop_the_world: p->state: %x\n", p->state));
624         if((p!=th) && ((p->state==STATE_RUNNING))) {
625             FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %x, os_thread %x\n",
626                           p, p->os_thread));
627             status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
628             if (status==ESRCH) {
629                 /* This thread has exited. */
630                 gc_assert(p->state==STATE_DEAD);
631             } else if (status) {
632                 lose("cannot send suspend thread=%lu: %d, %s\n",
633                      p->os_thread,status,strerror(status));
634             }
635         }
636     }
637     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
638     /* wait for the running threads to stop or finish */
639     for(p=all_threads;p;) {
640         FSHOW_SIGNAL((stderr,"/gc_stop_the_world: th: %p, p: %p\n", th, p));
641         if((p!=th) && (p->state==STATE_RUNNING)) {
642             sched_yield();
643         } else {
644             p=p->next;
645         }
646     }
647     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
648 }
649
650 void gc_start_the_world()
651 {
652     struct thread *p,*th=arch_os_get_current_thread();
653     int status, lock_ret;
654     /* if a resumed thread creates a new thread before we're done with
655      * this loop, the new thread will get consed on the front of
656      * all_threads, but it won't have been stopped so won't need
657      * restarting */
658     FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
659     for(p=all_threads;p;p=p->next) {
660         gc_assert(p->os_thread!=0);
661         if((p!=th) && (p->state!=STATE_DEAD)) {
662             if(p->state!=STATE_SUSPENDED) {
663                 lose("gc_start_the_world: wrong thread state is %d\n",
664                      fixnum_value(p->state));
665             }
666             FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
667                           p->os_thread));
668             p->state=STATE_RUNNING;
669
670 #if defined(SIG_RESUME_FROM_GC)
671             status=kill_thread_safely(p->os_thread,SIG_RESUME_FROM_GC);
672 #else
673             status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
674 #endif
675             if (status) {
676                 lose("cannot resume thread=%lu: %d, %s\n",
677                      p->os_thread,status,strerror(status));
678             }
679         }
680     }
681     /* If we waited here until all threads leave STATE_SUSPENDED, then
682      * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
683      * performance implications, but does away with the 'rt signal
684      * queue full' problem. */
685
686     lock_ret = pthread_mutex_unlock(&all_threads_lock);
687     gc_assert(lock_ret == 0);
688 #ifdef LOCK_CREATE_THREAD
689     lock_ret = pthread_mutex_unlock(&create_thread_lock);
690     gc_assert(lock_ret == 0);
691 #endif
692
693     FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
694 }
695 #endif