* Merged gc7-branch to default.
[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 lock_stopworld(int);
376 void unlock_stopworld();
377
378 void GC_stop_world()
379 {
380     int i;
381     int n_live_threads;
382     int code;
383
384     GC_ASSERT(I_HOLD_LOCK());
385 #   if DEBUG_THREADS
386       GC_printf("Stopping the world from 0x%x\n", (unsigned)pthread_self());
387 #   endif
388        
389     /* Make sure all free list construction has stopped before we start. */
390     /* No new construction can start, since free list construction is   */
391     /* required to acquire and release the GC lock before it starts,    */
392     /* and we have the lock.                                            */
393 #   ifdef PARALLEL_MARK
394       GC_acquire_mark_lock();
395       GC_ASSERT(GC_fl_builder_count == 0);
396       /* We should have previously waited for it to become zero. */
397 #   endif /* PARALLEL_MARK */
398     AO_store(&GC_stop_count, GC_stop_count+1);
399         /* Only concurrent reads are possible. */
400     AO_store_release(&GC_world_is_stopped, TRUE);
401     n_live_threads = GC_suspend_all();
402
403       if (GC_retry_signals) {
404           unsigned long wait_usecs = 0;  /* Total wait since retry.     */
405 #         define WAIT_UNIT 3000
406 #         define RETRY_INTERVAL 100000
407           for (;;) {
408               int ack_count;
409
410               sem_getvalue(&GC_suspend_ack_sem, &ack_count);
411               if (ack_count == n_live_threads) break;
412               if (wait_usecs > RETRY_INTERVAL) {
413                   int newly_sent = GC_suspend_all();
414
415                   if (GC_print_stats) {
416                       GC_log_printf("Resent %d signals after timeout\n",
417                                 newly_sent);
418                   }
419                   sem_getvalue(&GC_suspend_ack_sem, &ack_count);
420                   if (newly_sent < n_live_threads - ack_count) {
421                       WARN("Lost some threads during GC_stop_world?!\n",0);
422                       n_live_threads = ack_count + newly_sent;
423                   }
424                   wait_usecs = 0;
425               }
426               usleep(WAIT_UNIT);
427               wait_usecs += WAIT_UNIT;
428           }
429       }
430     for (i = 0; i < n_live_threads; i++) {
431         retry:
432           if (0 != (code = sem_wait(&GC_suspend_ack_sem))) {
433               /* On Linux, sem_wait is documented to always return zero.*/
434               /* But the documentation appears to be incorrect.         */
435               if (errno == EINTR) {
436                 /* Seems to happen with some versions of gdb.   */
437                 goto retry;
438               }
439               ABORT("sem_wait for handler failed");
440           }
441     }
442 #   ifdef PARALLEL_MARK
443       GC_release_mark_lock();
444 #   endif
445     #if DEBUG_THREADS
446       GC_printf("World stopped from 0x%x\n", (unsigned)pthread_self());
447     #endif
448     GC_stopping_thread = 0;  /* debugging only */
449 }
450
451 /* Caller holds allocation lock, and has held it continuously since     */
452 /* the world stopped.                                                   */
453 void GC_start_world()
454 {
455     pthread_t my_thread = pthread_self();
456     register int i;
457     register GC_thread p;
458     register int n_live_threads = 0;
459     register int result;
460 #   ifdef GC_NETBSD_THREADS_WORKAROUND
461       int code;
462 #   endif
463
464 #   if DEBUG_THREADS
465       GC_printf("World starting\n");
466 #   endif
467
468     AO_store(&GC_world_is_stopped, FALSE);
469     for (i = 0; i < THREAD_TABLE_SZ; i++) {
470       for (p = GC_threads[i]; p != 0; p = p -> next) {
471         if (!THREAD_EQUAL(p -> id, my_thread)) {
472             if (p -> flags & FINISHED) continue;
473             if (p -> thread_blocked) continue;
474             n_live_threads++;
475             #if DEBUG_THREADS
476               GC_printf("Sending restart signal to 0x%x\n",
477                         (unsigned)(p -> id));
478             #endif
479         
480             result = pthread_kill(p -> id, SIG_THR_RESTART);
481             switch(result) {
482                 case ESRCH:
483                     /* Not really there anymore.  Possible? */
484                     n_live_threads--;
485                     break;
486                 case 0:
487                     break;
488                 default:
489                     ABORT("pthread_kill failed");
490             }
491         }
492       }
493     }
494 #   ifdef GC_NETBSD_THREADS_WORKAROUND
495       for (i = 0; i < n_live_threads; i++)
496         while (0 != (code = sem_wait(&GC_restart_ack_sem)))
497             if (errno != EINTR) {
498                 GC_err_printf("sem_wait() returned %d\n",
499                                code);
500                 ABORT("sem_wait() for restart handler failed");
501             }
502 #    endif
503 #    if DEBUG_THREADS
504       GC_printf("World started\n");
505 #    endif
506 }
507
508 void GC_stop_init() {
509     struct sigaction act;
510     
511     if (sem_init(&GC_suspend_ack_sem, 0, 0) != 0)
512         ABORT("sem_init failed");
513 #   ifdef GC_NETBSD_THREADS_WORKAROUND
514       if (sem_init(&GC_restart_ack_sem, 0, 0) != 0)
515         ABORT("sem_init failed");
516 #   endif
517
518     act.sa_flags = SA_RESTART
519 #   ifdef SA_SIGINFO
520         | SA_SIGINFO
521 #   endif
522         ;
523     if (sigfillset(&act.sa_mask) != 0) {
524         ABORT("sigfillset() failed");
525     }
526     GC_remove_allowed_signals(&act.sa_mask);
527     /* SIG_THR_RESTART is set in the resulting mask.            */
528     /* It is unmasked by the handler when necessary.            */
529 #   ifdef SA_SIGINFO
530     act.sa_sigaction = GC_suspend_handler;
531 #   else
532     act.sa_handler = GC_suspend_handler;
533 #   endif
534     if (sigaction(SIG_SUSPEND, &act, NULL) != 0) {
535         ABORT("Cannot set SIG_SUSPEND handler");
536     }
537
538 #   ifdef SA_SIGINFO
539     act.sa_flags &= ~ SA_SIGINFO;
540 #   endif
541     act.sa_handler = GC_restart_handler;
542     if (sigaction(SIG_THR_RESTART, &act, NULL) != 0) {
543         ABORT("Cannot set SIG_THR_RESTART handler");
544     }
545
546     /* Inititialize suspend_handler_mask. It excludes SIG_THR_RESTART. */
547       if (sigfillset(&suspend_handler_mask) != 0) ABORT("sigfillset() failed");
548       GC_remove_allowed_signals(&suspend_handler_mask);
549       if (sigdelset(&suspend_handler_mask, SIG_THR_RESTART) != 0)
550           ABORT("sigdelset() failed");
551
552     /* Check for GC_RETRY_SIGNALS.      */
553       if (0 != GETENV("GC_RETRY_SIGNALS")) {
554           GC_retry_signals = TRUE;
555       }
556       if (0 != GETENV("GC_NO_RETRY_SIGNALS")) {
557           GC_retry_signals = FALSE;
558       }
559       if (GC_print_stats && GC_retry_signals) {
560           GC_log_printf("Will retry suspend signal if necessary.\n");
561       }
562 }
563
564 /* Added for cacao */
565 int GC_signum1()
566 {
567     return SIG_SUSPEND;
568 }
569
570 int GC_signum2()
571 {
572     return SIG_THR_RESTART;
573 }
574 /* cacao END */
575
576 #endif