boehm-gc: revert all CACAO-specific modifications; this is now an exact copy of the...
[cacao.git] / src / mm / boehm-gc / pthread_stop_world.c
1 #include "private/pthread_support.h"
2
3 #if defined(GC_PTHREADS) && !defined(GC_WIN32_THREADS) && \
4     !defined(GC_DARWIN_THREADS)
5
6 #include <signal.h>
7 #include <semaphore.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include "atomic_ops.h"
11
12 #if DEBUG_THREADS
13
14 #ifndef NSIG
15 # if defined(MAXSIG)
16 #  define NSIG (MAXSIG+1)
17 # elif defined(_NSIG)
18 #  define NSIG _NSIG
19 # elif defined(__SIGRTMAX)
20 #  define NSIG (__SIGRTMAX+1)
21 # else
22   --> please fix it
23 # endif
24 #endif
25
26 void GC_print_sig_mask(void)
27 {
28     sigset_t blocked;
29     int i;
30
31     if (pthread_sigmask(SIG_BLOCK, NULL, &blocked) != 0)
32         ABORT("pthread_sigmask");
33     GC_printf("Blocked: ");
34     for (i = 1; i < NSIG; i++) {
35         if (sigismember(&blocked, i)) { GC_printf("%d ", i); }
36     }
37     GC_printf("\n");
38 }
39
40 #endif
41
42 /* Remove the signals that we want to allow in thread stopping  */
43 /* handler from a set.                                          */
44 STATIC void GC_remove_allowed_signals(sigset_t *set)
45 {
46     if (sigdelset(set, SIGINT) != 0
47           || sigdelset(set, SIGQUIT) != 0
48           || sigdelset(set, SIGABRT) != 0
49           || sigdelset(set, SIGTERM) != 0) {
50         ABORT("sigdelset() failed");
51     }
52
53 #   ifdef MPROTECT_VDB
54       /* Handlers write to the thread structure, which is in the heap,  */
55       /* and hence can trigger a protection fault.                      */
56       if (sigdelset(set, SIGSEGV) != 0
57 #         ifdef SIGBUS
58             || sigdelset(set, SIGBUS) != 0
59 #         endif
60           ) {
61         ABORT("sigdelset() failed");
62       }
63 #   endif
64 }
65
66 static sigset_t suspend_handler_mask;
67
68 volatile AO_t GC_stop_count;
69                         /* Incremented at the beginning of GC_stop_world. */
70
71 volatile AO_t GC_world_is_stopped = FALSE;
72                         /* FALSE ==> it is safe for threads to restart, i.e. */
73                         /* they will see another suspend signal before they  */
74                         /* are expected to stop (unless they have voluntarily */
75                         /* stopped).                                         */
76
77 #ifdef GC_OSF1_THREADS
78   STATIC GC_bool GC_retry_signals = TRUE;
79 #else
80   STATIC GC_bool GC_retry_signals = FALSE;
81 #endif
82
83 /*
84  * We use signals to stop threads during GC.
85  * 
86  * Suspended threads wait in signal handler for SIG_THR_RESTART.
87  * That's more portable than semaphores or condition variables.
88  * (We do use sem_post from a signal handler, but that should be portable.)
89  *
90  * The thread suspension signal SIG_SUSPEND is now defined in gc_priv.h.
91  * Note that we can't just stop a thread; we need it to save its stack
92  * pointer(s) and acknowledge.
93  */
94
95 #ifndef SIG_THR_RESTART
96 #  if defined(GC_HPUX_THREADS) || defined(GC_OSF1_THREADS) || defined(GC_NETBSD_THREADS)
97 #    ifdef _SIGRTMIN
98 #      define SIG_THR_RESTART _SIGRTMIN + 5
99 #    else
100 #      define SIG_THR_RESTART SIGRTMIN + 5
101 #    endif
102 #  else
103 #   define SIG_THR_RESTART SIGXCPU
104 #  endif
105 #endif
106
107 STATIC sem_t GC_suspend_ack_sem;
108
109 #ifdef GC_NETBSD_THREADS
110 # define GC_NETBSD_THREADS_WORKAROUND
111   /* It seems to be necessary to wait until threads have restarted.     */
112   /* But it is unclear why that is the case.                            */
113   STATIC sem_t GC_restart_ack_sem;
114 #endif
115
116 STATIC void GC_suspend_handler_inner(ptr_t sig_arg, void *context);
117
118 #if defined(IA64) || defined(HP_PA) || defined(M68K)
119 #ifdef SA_SIGINFO
120 /*ARGSUSED*/
121 STATIC void GC_suspend_handler(int sig, siginfo_t *info, void *context)
122 #else
123 STATIC void GC_suspend_handler(int sig)
124 #endif
125 {
126   int old_errno = errno;
127   GC_with_callee_saves_pushed(GC_suspend_handler_inner, (ptr_t)(word)sig);
128   errno = old_errno;
129 }
130 #else
131 /* We believe that in all other cases the full context is already       */
132 /* in the signal handler frame.                                         */
133 #ifdef SA_SIGINFO
134 STATIC void GC_suspend_handler(int sig, siginfo_t *info, void *context)
135 #else
136 STATIC void GC_suspend_handler(int sig)
137 #endif
138 {
139   int old_errno = errno;
140 # ifndef SA_SIGINFO
141     void *context = 0;
142 # endif
143   GC_suspend_handler_inner((ptr_t)(word)sig, context);
144   errno = old_errno;
145 }
146 #endif
147
148 /*ARGSUSED*/
149 STATIC void GC_suspend_handler_inner(ptr_t sig_arg, void *context)
150 {
151     int sig = (int)(word)sig_arg;
152     int dummy;
153     pthread_t my_thread = pthread_self();
154     GC_thread me;
155
156     AO_t my_stop_count = AO_load(&GC_stop_count);
157
158     if (sig != SIG_SUSPEND) ABORT("Bad signal in suspend_handler");
159
160 #   if DEBUG_THREADS
161       GC_printf("Suspending 0x%x\n", (unsigned)my_thread);
162 #   endif
163
164     me = GC_lookup_thread(my_thread);
165     /* The lookup here is safe, since I'm doing this on behalf  */
166     /* of a thread which holds the allocation lock in order     */
167     /* to stop the world.  Thus concurrent modification of the  */
168     /* data structure is impossible.                            */
169     if (me -> stop_info.last_stop_count == my_stop_count) {
170         /* Duplicate signal.  OK if we are retrying.    */
171         if (!GC_retry_signals) {
172             WARN("Duplicate suspend signal in thread %p\n",
173                  (word)pthread_self());
174         }
175         return;
176     }
177 #   ifdef SPARC
178         me -> stop_info.stack_ptr = GC_save_regs_in_stack();
179 #   else
180         me -> stop_info.stack_ptr = (ptr_t)(&dummy);
181 #   endif
182 #   ifdef IA64
183         me -> backing_store_ptr = GC_save_regs_in_stack();
184 #   endif
185
186     /* Tell the thread that wants to stop the world that this   */
187     /* thread has been stopped.  Note that sem_post() is        */
188     /* the only async-signal-safe primitive in LinuxThreads.    */
189     sem_post(&GC_suspend_ack_sem);
190     me -> stop_info.last_stop_count = my_stop_count;
191
192     /* Wait until that thread tells us to restart by sending    */
193     /* this thread a SIG_THR_RESTART signal.                    */
194     /* SIG_THR_RESTART should be masked at this point.  Thus there      */
195     /* is no race.                                              */
196     /* We do not continue until we receive a SIG_THR_RESTART,   */
197     /* but we do not take that as authoritative.  (We may be    */
198     /* accidentally restarted by one of the user signals we     */
199     /* don't block.)  After we receive the signal, we use a     */
200     /* primitive and expensive mechanism to wait until it's     */
201     /* really safe to proceed.  Under normal circumstances,     */
202     /* this code should not be executed.                        */
203     do {
204         sigsuspend (&suspend_handler_mask);
205     } while (AO_load_acquire(&GC_world_is_stopped)
206              && AO_load(&GC_stop_count) == my_stop_count);
207     /* If the RESTART signal gets lost, we can still lose.  That should be  */
208     /* less likely than losing the SUSPEND signal, since we don't do much   */
209     /* between the sem_post and sigsuspend.                                 */
210     /* We'd need more handshaking to work around that.                      */
211     /* Simply dropping the sigsuspend call should be safe, but is unlikely  */
212     /* to be efficient.                                                     */
213
214 #   if DEBUG_THREADS
215       GC_printf("Continuing 0x%x\n", (unsigned)my_thread);
216 #   endif
217 }
218
219 STATIC void GC_restart_handler(int sig)
220 {
221     if (sig != SIG_THR_RESTART) ABORT("Bad signal in suspend_handler");
222
223 #   ifdef GC_NETBSD_THREADS_WORKAROUND
224       sem_post(&GC_restart_ack_sem);
225 #   endif
226
227     /*
228     ** Note: even if we don't do anything useful here,
229     ** it would still be necessary to have a signal handler,
230     ** rather than ignoring the signals, otherwise
231     ** the signals will not be delivered at all, and
232     ** will thus not interrupt the sigsuspend() above.
233     */
234
235 #   if DEBUG_THREADS
236       GC_printf("In GC_restart_handler for 0x%x\n", (unsigned)pthread_self());
237 #   endif
238 }
239
240 void GC_thr_init(void);
241
242 # ifdef IA64
243 #   define IF_IA64(x) x
244 # else
245 #   define IF_IA64(x)
246 # endif
247 /* We hold allocation lock.  Should do exactly the right thing if the   */
248 /* world is stopped.  Should not fail if it isn't.                      */
249 void GC_push_all_stacks(void)
250 {
251     GC_bool found_me = FALSE;
252     size_t nthreads = 0;
253     int i;
254     GC_thread p;
255     ptr_t lo, hi;
256     /* On IA64, we also need to scan the register backing store. */
257     IF_IA64(ptr_t bs_lo; ptr_t bs_hi;)
258     pthread_t me = pthread_self();
259     
260     if (!GC_thr_initialized) GC_thr_init();
261 #   if DEBUG_THREADS
262         GC_printf("Pushing stacks from thread 0x%x\n", (unsigned) me);
263 #   endif
264     for (i = 0; i < THREAD_TABLE_SZ; i++) {
265       for (p = GC_threads[i]; p != 0; p = p -> next) {
266         if (p -> flags & FINISHED) continue;
267         ++nthreads;
268         if (THREAD_EQUAL(p -> id, me)) {
269             GC_ASSERT(!p->thread_blocked);
270 #           ifdef SPARC
271                 lo = (ptr_t)GC_save_regs_in_stack();
272 #           else
273                 lo = GC_approx_sp();
274 #           endif
275             found_me = TRUE;
276             IF_IA64(bs_hi = (ptr_t)GC_save_regs_in_stack();)
277         } else {
278             lo = p -> stop_info.stack_ptr;
279             IF_IA64(bs_hi = p -> backing_store_ptr;)
280         }
281         if ((p -> flags & MAIN_THREAD) == 0) {
282             hi = p -> stack_end;
283             IF_IA64(bs_lo = p -> backing_store_end);
284         } else {
285             /* The original stack. */
286             hi = GC_stackbottom;
287             IF_IA64(bs_lo = BACKING_STORE_BASE;)
288         }
289 #       if DEBUG_THREADS
290             GC_printf("Stack for thread 0x%x = [%p,%p)\n",
291                       (unsigned)(p -> id), lo, hi);
292 #       endif
293         if (0 == lo) ABORT("GC_push_all_stacks: sp not set!\n");
294 #       ifdef STACK_GROWS_UP
295           /* We got them backwards! */
296           GC_push_all_stack(hi, lo);
297 #       else
298           GC_push_all_stack(lo, hi);
299 #       endif
300 #       ifdef IA64
301 #         if DEBUG_THREADS
302             GC_printf("Reg stack for thread 0x%x = [%p,%p)\n",
303                       (unsigned)p -> id, bs_lo, bs_hi);
304 #         endif
305           if (THREAD_EQUAL(p -> id, me)) {
306             /* FIXME:  This may add an unbounded number of entries,     */
307             /* and hence overflow the mark stack, which is bad.         */
308             GC_push_all_eager(bs_lo, bs_hi);
309           } else {
310             GC_push_all_stack(bs_lo, bs_hi);
311           }
312 #       endif
313       }
314     }
315     if (GC_print_stats == VERBOSE) {
316         GC_log_printf("Pushed %d thread stacks\n", (int)nthreads);
317     }
318     if (!found_me && !GC_in_thread_creation)
319       ABORT("Collecting from unknown thread.");
320 }
321
322 /* There seems to be a very rare thread stopping problem.  To help us  */
323 /* debug that, we save the ids of the stopping thread. */
324 #if DEBUG_THREADS
325 pthread_t GC_stopping_thread;
326 int GC_stopping_pid;
327 #endif
328
329 /* We hold the allocation lock.  Suspend all threads that might */
330 /* still be running.  Return the number of suspend signals that */
331 /* were sent. */
332 STATIC int GC_suspend_all(void)
333 {
334     int n_live_threads = 0;
335     int i;
336     GC_thread p;
337     int result;
338     pthread_t my_thread = pthread_self();
339     
340 #   if DEBUG_THREADS
341       GC_stopping_thread = my_thread;
342       GC_stopping_pid = getpid();
343 #   endif
344     for (i = 0; i < THREAD_TABLE_SZ; i++) {
345       for (p = GC_threads[i]; p != 0; p = p -> next) {
346         if (!THREAD_EQUAL(p -> id, my_thread)) {
347             if (p -> flags & FINISHED) continue;
348             if (p -> stop_info.last_stop_count == GC_stop_count) continue;
349             if (p -> thread_blocked) /* Will wait */ continue;
350             n_live_threads++;
351 #           if DEBUG_THREADS
352               GC_printf("Sending suspend signal to 0x%x\n",
353                         (unsigned)(p -> id));
354 #           endif
355         
356             result = pthread_kill(p -> id, SIG_SUSPEND);
357             switch(result) {
358                 case ESRCH:
359                     /* Not really there anymore.  Possible? */
360                     n_live_threads--;
361                     break;
362                 case 0:
363                     break;
364                 default:
365                     ABORT("pthread_kill failed");
366             }
367         }
368       }
369     }
370     return n_live_threads;
371 }
372
373 void GC_stop_world(void)
374 {
375     int i;
376     int n_live_threads;
377     int code;
378
379     GC_ASSERT(I_HOLD_LOCK());
380 #   if DEBUG_THREADS
381       GC_printf("Stopping the world from 0x%x\n", (unsigned)pthread_self());
382 #   endif
383        
384     /* Make sure all free list construction has stopped before we start. */
385     /* No new construction can start, since free list construction is   */
386     /* required to acquire and release the GC lock before it starts,    */
387     /* and we have the lock.                                            */
388 #   ifdef PARALLEL_MARK
389       if (GC_parallel) {
390         GC_acquire_mark_lock();
391         GC_ASSERT(GC_fl_builder_count == 0);
392         /* We should have previously waited for it to become zero. */
393       }
394 #   endif /* PARALLEL_MARK */
395     AO_store(&GC_stop_count, GC_stop_count+1);
396         /* Only concurrent reads are possible. */
397     AO_store_release(&GC_world_is_stopped, TRUE);
398     n_live_threads = GC_suspend_all();
399
400       if (GC_retry_signals) {
401           unsigned long wait_usecs = 0;  /* Total wait since retry.     */
402 #         define WAIT_UNIT 3000
403 #         define RETRY_INTERVAL 100000
404           for (;;) {
405               int ack_count;
406
407               sem_getvalue(&GC_suspend_ack_sem, &ack_count);
408               if (ack_count == n_live_threads) break;
409               if (wait_usecs > RETRY_INTERVAL) {
410                   int newly_sent = GC_suspend_all();
411
412                   if (GC_print_stats) {
413                       GC_log_printf("Resent %d signals after timeout\n",
414                                 newly_sent);
415                   }
416                   sem_getvalue(&GC_suspend_ack_sem, &ack_count);
417                   if (newly_sent < n_live_threads - ack_count) {
418                       WARN("Lost some threads during GC_stop_world?!\n",0);
419                       n_live_threads = ack_count + newly_sent;
420                   }
421                   wait_usecs = 0;
422               }
423               usleep(WAIT_UNIT);
424               wait_usecs += WAIT_UNIT;
425           }
426       }
427     for (i = 0; i < n_live_threads; i++) {
428         retry:
429           if (0 != (code = sem_wait(&GC_suspend_ack_sem))) {
430               /* On Linux, sem_wait is documented to always return zero.*/
431               /* But the documentation appears to be incorrect.         */
432               if (errno == EINTR) {
433                 /* Seems to happen with some versions of gdb.   */
434                 goto retry;
435               }
436               ABORT("sem_wait for handler failed");
437           }
438     }
439 #   ifdef PARALLEL_MARK
440       if (GC_parallel)
441         GC_release_mark_lock();
442 #   endif
443 #   if DEBUG_THREADS
444       GC_printf("World stopped from 0x%x\n", (unsigned)pthread_self());
445       GC_stopping_thread = 0;
446 #   endif
447 }
448
449 /* Caller holds allocation lock, and has held it continuously since     */
450 /* the world stopped.                                                   */
451 void GC_start_world(void)
452 {
453     pthread_t my_thread = pthread_self();
454     register int i;
455     register GC_thread p;
456     register int n_live_threads = 0;
457     register int result;
458 #   ifdef GC_NETBSD_THREADS_WORKAROUND
459       int code;
460 #   endif
461
462 #   if DEBUG_THREADS
463       GC_printf("World starting\n");
464 #   endif
465
466     AO_store(&GC_world_is_stopped, FALSE);
467     for (i = 0; i < THREAD_TABLE_SZ; i++) {
468       for (p = GC_threads[i]; p != 0; p = p -> next) {
469         if (!THREAD_EQUAL(p -> id, my_thread)) {
470             if (p -> flags & FINISHED) continue;
471             if (p -> thread_blocked) continue;
472             n_live_threads++;
473 #           if DEBUG_THREADS
474               GC_printf("Sending restart signal to 0x%x\n",
475                         (unsigned)(p -> id));
476 #           endif
477         
478             result = pthread_kill(p -> id, SIG_THR_RESTART);
479             switch(result) {
480                 case ESRCH:
481                     /* Not really there anymore.  Possible? */
482                     n_live_threads--;
483                     break;
484                 case 0:
485                     break;
486                 default:
487                     ABORT("pthread_kill failed");
488             }
489         }
490       }
491     }
492 #   ifdef GC_NETBSD_THREADS_WORKAROUND
493       for (i = 0; i < n_live_threads; i++)
494         while (0 != (code = sem_wait(&GC_restart_ack_sem)))
495             if (errno != EINTR) {
496                 GC_err_printf("sem_wait() returned %d\n",
497                                code);
498                 ABORT("sem_wait() for restart handler failed");
499             }
500 #    endif
501 #    if DEBUG_THREADS
502       GC_printf("World started\n");
503 #    endif
504 }
505
506 void GC_stop_init(void) {
507     struct sigaction act;
508     
509     if (sem_init(&GC_suspend_ack_sem, 0, 0) != 0)
510         ABORT("sem_init failed");
511 #   ifdef GC_NETBSD_THREADS_WORKAROUND
512       if (sem_init(&GC_restart_ack_sem, 0, 0) != 0)
513         ABORT("sem_init failed");
514 #   endif
515
516     act.sa_flags = SA_RESTART
517 #   ifdef SA_SIGINFO
518         | SA_SIGINFO
519 #   endif
520         ;
521     if (sigfillset(&act.sa_mask) != 0) {
522         ABORT("sigfillset() failed");
523     }
524     GC_remove_allowed_signals(&act.sa_mask);
525     /* SIG_THR_RESTART is set in the resulting mask.            */
526     /* It is unmasked by the handler when necessary.            */
527 #   ifdef SA_SIGINFO
528     act.sa_sigaction = GC_suspend_handler;
529 #   else
530     act.sa_handler = GC_suspend_handler;
531 #   endif
532     if (sigaction(SIG_SUSPEND, &act, NULL) != 0) {
533         ABORT("Cannot set SIG_SUSPEND handler");
534     }
535
536 #   ifdef SA_SIGINFO
537     act.sa_flags &= ~ SA_SIGINFO;
538 #   endif
539     act.sa_handler = GC_restart_handler;
540     if (sigaction(SIG_THR_RESTART, &act, NULL) != 0) {
541         ABORT("Cannot set SIG_THR_RESTART handler");
542     }
543
544     /* Initialize suspend_handler_mask. It excludes SIG_THR_RESTART. */
545       if (sigfillset(&suspend_handler_mask) != 0) ABORT("sigfillset() failed");
546       GC_remove_allowed_signals(&suspend_handler_mask);
547       if (sigdelset(&suspend_handler_mask, SIG_THR_RESTART) != 0)
548           ABORT("sigdelset() failed");
549
550     /* Check for GC_RETRY_SIGNALS.      */
551       if (0 != GETENV("GC_RETRY_SIGNALS")) {
552           GC_retry_signals = TRUE;
553       }
554       if (0 != GETENV("GC_NO_RETRY_SIGNALS")) {
555           GC_retry_signals = FALSE;
556       }
557       if (GC_print_stats && GC_retry_signals) {
558           GC_log_printf("Will retry suspend signal if necessary.\n");
559       }
560 }
561
562 #endif