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