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