Clean merge -> gc7-branch
[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 void GC_suspend_handler(int sig, siginfo_t *info, void *context)
123 {
124    int old_errno = errno;
125    GC_with_callee_saves_pushed(GC_suspend_handler_inner, (ptr_t)(word)sig);
126    errno = old_errno;
127 }
128 #else
129 /* We believe that in all other cases the full context is already       */
130 /* in the signal handler frame.                                         */
131 void GC_suspend_handler(int sig, siginfo_t *info, void *context)
132 {
133    int old_errno = errno;
134
135 /*    if (cacao_suspendhandler(uctx)) */
136 /*      return; */
137
138    GC_suspend_handler_inner((ptr_t)(word)sig, context);
139    errno = old_errno;
140 }
141 #endif
142
143 void GC_suspend_handler_inner(ptr_t sig_arg, void *context)
144 {
145     int sig = (int)(word)sig_arg;
146     int dummy;
147     pthread_t my_thread = pthread_self();
148     GC_thread me;
149 #   ifdef PARALLEL_MARK
150         word my_mark_no = GC_mark_no;
151         /* Marker can't proceed until we acknowledge.  Thus this is     */
152         /* guaranteed to be the mark_no correspending to our            */
153         /* suspension, i.e. the marker can't have incremented it yet.   */
154 #   endif
155     AO_t my_stop_count = AO_load(&GC_stop_count);
156
157     if (sig != SIG_SUSPEND) ABORT("Bad signal in suspend_handler");
158
159 #   if DEBUG_THREADS
160       GC_printf("Suspending 0x%x\n", (unsigned)my_thread);
161 #   endif
162
163     me = GC_lookup_thread(my_thread);
164     /* The lookup here is safe, since I'm doing this on behalf  */
165     /* of a thread which holds the allocation lock in order     */
166     /* to stop the world.  Thus concurrent modification of the  */
167     /* data structure is impossible.                            */
168     if (me -> stop_info.last_stop_count == my_stop_count) {
169         /* Duplicate signal.  OK if we are retrying.    */
170         if (!GC_retry_signals) {
171             WARN("Duplicate suspend signal in thread %lx\n",
172                  pthread_self());
173         }
174         return;
175     }
176 #   ifdef SPARC
177         me -> stop_info.stack_ptr = GC_save_regs_in_stack();
178 #   else
179         me -> stop_info.stack_ptr = (ptr_t)(&dummy);
180 #   endif
181 #   ifdef IA64
182         me -> backing_store_ptr = GC_save_regs_in_stack();
183 #   endif
184
185     /* Tell the thread that wants to stop the world that this   */
186     /* thread has been stopped.  Note that sem_post() is        */
187     /* the only async-signal-safe primitive in LinuxThreads.    */
188     sem_post(&GC_suspend_ack_sem);
189     me -> stop_info.last_stop_count = my_stop_count;
190
191     /* Wait until that thread tells us to restart by sending    */
192     /* this thread a SIG_THR_RESTART signal.                    */
193     /* SIG_THR_RESTART should be masked at this point.  Thus there      */
194     /* is no race.                                              */
195     /* We do not continue until we receive a SIG_THR_RESTART,   */
196     /* but we do not take that as authoritative.  (We may be    */
197     /* accidentally restarted by one of the user signals we     */
198     /* don't block.)  After we receive the signal, we use a     */
199     /* primitive and expensive mechanism to wait until it's     */
200     /* really safe to proceed.  Under normal circumstances,     */
201     /* this code should not be executed.                        */
202     do {
203         sigsuspend (&suspend_handler_mask);
204     } while (AO_load_acquire(&GC_world_is_stopped)
205              && AO_load(&GC_stop_count) == my_stop_count);
206     /* If the RESTART signal gets lost, we can still lose.  That should be  */
207     /* less likely than losing the SUSPEND signal, since we don't do much   */
208     /* between the sem_post and sigsuspend.                                 */
209     /* We'd need more handshaking to work around that.                      */
210     /* Simply dropping the sigsuspend call should be safe, but is unlikely  */
211     /* to be efficient.                                                     */
212
213 #   if DEBUG_THREADS
214       GC_printf("Continuing 0x%x\n", (unsigned)my_thread);
215 #   endif
216 }
217
218 void GC_restart_handler(int sig)
219 {
220     pthread_t my_thread = pthread_self();
221     GC_thread me;
222
223     if (sig != SIG_THR_RESTART) ABORT("Bad signal in suspend_handler");
224
225 #   ifdef GC_NETBSD_THREADS_WORKAROUND
226       sem_post(&GC_restart_ack_sem);
227 #   endif
228
229     /*
230     ** Note: even if we don't do anything useful here,
231     ** it would still be necessary to have a signal handler,
232     ** rather than ignoring the signals, otherwise
233     ** the signals will not be delivered at all, and
234     ** will thus not interrupt the sigsuspend() above.
235     */
236
237 #   if DEBUG_THREADS
238       GC_printf("In GC_restart_handler for 0x%x\n", (unsigned)pthread_self());
239 #   endif
240 }
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()
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 #           ifdef SPARC
270                 lo = (ptr_t)GC_save_regs_in_stack();
271 #           else
272                 lo = GC_approx_sp();
273 #           endif
274             found_me = TRUE;
275             IF_IA64(bs_hi = (ptr_t)GC_save_regs_in_stack();)
276         } else {
277             lo = p -> stop_info.stack_ptr;
278             IF_IA64(bs_hi = p -> backing_store_ptr;)
279         }
280         if ((p -> flags & MAIN_THREAD) == 0) {
281             hi = p -> stack_end;
282             IF_IA64(bs_lo = p -> backing_store_end);
283         } else {
284             /* The original stack. */
285             hi = GC_stackbottom;
286             IF_IA64(bs_lo = BACKING_STORE_BASE;)
287         }
288 #       if DEBUG_THREADS
289             GC_printf("Stack for thread 0x%x = [%p,%p)\n",
290                       (unsigned)(p -> id), lo, hi);
291 #       endif
292         if (0 == lo) ABORT("GC_push_all_stacks: sp not set!\n");
293 #       ifdef STACK_GROWS_UP
294           /* We got them backwards! */
295           GC_push_all_stack(hi, lo);
296 #       else
297           GC_push_all_stack(lo, hi);
298 #       endif
299 #       ifdef IA64
300 #         if DEBUG_THREADS
301             GC_printf("Reg stack for thread 0x%x = [%lx,%lx)\n",
302                       (unsigned)p -> id, bs_lo, bs_hi);
303 #         endif
304           if (THREAD_EQUAL(p -> id, me)) {
305             /* FIXME:  This may add an unbounded number of entries,     */
306             /* and hence overflow the mark stack, which is bad.         */
307             GC_push_all_eager(bs_lo, bs_hi);
308           } else {
309             GC_push_all_stack(bs_lo, bs_hi);
310           }
311 #       endif
312       }
313     }
314     if (GC_print_stats == VERBOSE) {
315         GC_log_printf("Pushed %d thread stacks\n", nthreads);
316     }
317     if (!found_me && !GC_in_thread_creation)
318       ABORT("Collecting from unknown thread.");
319 }
320
321 /* There seems to be a very rare thread stopping problem.  To help us  */
322 /* debug that, we save the ids of the stopping thread. */
323 pthread_t GC_stopping_thread;
324 int GC_stopping_pid;
325
326 /* We hold the allocation lock.  Suspend all threads that might */
327 /* still be running.  Return the number of suspend signals that */
328 /* were sent. */
329 int GC_suspend_all()
330 {
331     int n_live_threads = 0;
332     int i;
333     GC_thread p;
334     int result;
335     pthread_t my_thread = pthread_self();
336     
337     GC_stopping_thread = my_thread;    /* debugging only.      */
338     GC_stopping_pid = getpid();                /* debugging only.      */
339     for (i = 0; i < THREAD_TABLE_SZ; i++) {
340       for (p = GC_threads[i]; p != 0; p = p -> next) {
341         if (!THREAD_EQUAL(p -> id, my_thread)) {
342             if (p -> flags & FINISHED) continue;
343             if (p -> stop_info.last_stop_count == GC_stop_count) continue;
344             if (p -> thread_blocked) /* Will wait */ continue;
345             n_live_threads++;
346 #           if DEBUG_THREADS
347               GC_printf("Sending suspend signal to 0x%x\n",
348                         (unsigned)(p -> id));
349 #           endif
350         
351             result = pthread_kill(p -> id, SIG_SUSPEND);
352             switch(result) {
353                 case ESRCH:
354                     /* Not really there anymore.  Possible? */
355                     n_live_threads--;
356                     break;
357                 case 0:
358                     break;
359                 default:
360                     ABORT("pthread_kill failed");
361             }
362         }
363       }
364     }
365     return n_live_threads;
366 }
367
368 void lock_stopworld(int);
369 void unlock_stopworld();
370
371 void GC_stop_world()
372 {
373     int i;
374     int n_live_threads;
375     int code;
376
377     GC_ASSERT(I_HOLD_LOCK());
378 #   if DEBUG_THREADS
379       GC_printf("Stopping the world from 0x%x\n", (unsigned)pthread_self());
380 #   endif
381
382     lock_stopworld(1);
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       GC_acquire_mark_lock();
390       GC_ASSERT(GC_fl_builder_count == 0);
391       /* We should have previously waited for it to become zero. */
392 #   endif /* PARALLEL_MARK */
393     AO_store(&GC_stop_count, GC_stop_count+1);
394         /* Only concurrent reads are possible. */
395     AO_store_release(&GC_world_is_stopped, TRUE);
396     n_live_threads = GC_suspend_all();
397
398       if (GC_retry_signals) {
399           unsigned long wait_usecs = 0;  /* Total wait since retry.     */
400 #         define WAIT_UNIT 3000
401 #         define RETRY_INTERVAL 100000
402           for (;;) {
403               int ack_count;
404
405               sem_getvalue(&GC_suspend_ack_sem, &ack_count);
406               if (ack_count == n_live_threads) break;
407               if (wait_usecs > RETRY_INTERVAL) {
408                   int newly_sent = GC_suspend_all();
409
410                   if (GC_print_stats) {
411                       GC_log_printf("Resent %d signals after timeout\n",
412                                 newly_sent);
413                   }
414                   sem_getvalue(&GC_suspend_ack_sem, &ack_count);
415                   if (newly_sent < n_live_threads - ack_count) {
416                       WARN("Lost some threads during GC_stop_world?!\n",0);
417                       n_live_threads = ack_count + newly_sent;
418                   }
419                   wait_usecs = 0;
420               }
421               usleep(WAIT_UNIT);
422               wait_usecs += WAIT_UNIT;
423           }
424       }
425     for (i = 0; i < n_live_threads; i++) {
426         retry:
427           if (0 != (code = sem_wait(&GC_suspend_ack_sem))) {
428               /* On Linux, sem_wait is documented to always return zero.*/
429               /* But the documentation appears to be incorrect.         */
430               if (errno == EINTR) {
431                 /* Seems to happen with some versions of gdb.   */
432                 goto retry;
433               }
434               ABORT("sem_wait for handler failed");
435           }
436     }
437 #   ifdef PARALLEL_MARK
438       GC_release_mark_lock();
439 #   endif
440     #if DEBUG_THREADS
441       GC_printf("World stopped from 0x%x\n", (unsigned)pthread_self());
442     #endif
443     GC_stopping_thread = 0;  /* debugging only */
444 }
445
446 /* Caller holds allocation lock, and has held it continuously since     */
447 /* the world stopped.                                                   */
448 void GC_start_world()
449 {
450     pthread_t my_thread = pthread_self();
451     register int i;
452     register GC_thread p;
453     register int n_live_threads = 0;
454     register int result;
455 #   ifdef GC_NETBSD_THREADS_WORKAROUND
456       int code;
457 #   endif
458
459 #   if DEBUG_THREADS
460       GC_printf("World starting\n");
461 #   endif
462
463     AO_store(&GC_world_is_stopped, FALSE);
464     for (i = 0; i < THREAD_TABLE_SZ; i++) {
465       for (p = GC_threads[i]; p != 0; p = p -> next) {
466         if (!THREAD_EQUAL(p -> id, my_thread)) {
467             if (p -> flags & FINISHED) continue;
468             if (p -> thread_blocked) continue;
469             n_live_threads++;
470             #if DEBUG_THREADS
471               GC_printf("Sending restart signal to 0x%x\n",
472                         (unsigned)(p -> id));
473             #endif
474         
475             result = pthread_kill(p -> id, SIG_THR_RESTART);
476             switch(result) {
477                 case ESRCH:
478                     /* Not really there anymore.  Possible? */
479                     n_live_threads--;
480                     break;
481                 case 0:
482                     break;
483                 default:
484                     ABORT("pthread_kill failed");
485             }
486         }
487       }
488     }
489 #   ifdef GC_NETBSD_THREADS_WORKAROUND
490       for (i = 0; i < n_live_threads; i++)
491         while (0 != (code = sem_wait(&GC_restart_ack_sem)))
492             if (errno != EINTR) {
493                 GC_err_printf1("sem_wait() returned %ld\n",
494                                (unsigned long)code);
495                 ABORT("sem_wait() for restart handler failed");
496             }
497 #    endif
498
499         unlock_stopworld();
500
501 #    if DEBUG_THREADS
502       GC_printf("World started\n");
503 #    endif
504 }
505
506 void GC_stop_init() {
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 | SA_SIGINFO;
517     if (sigfillset(&act.sa_mask) != 0) {
518         ABORT("sigfillset() failed");
519     }
520     GC_remove_allowed_signals(&act.sa_mask);
521     /* SIG_THR_RESTART is set in the resulting mask.            */
522     /* It is unmasked by the handler when necessary.            */
523     act.sa_sigaction = GC_suspend_handler;
524     if (sigaction(SIG_SUSPEND, &act, NULL) != 0) {
525         ABORT("Cannot set SIG_SUSPEND handler");
526     }
527
528     act.sa_flags &= ~ SA_SIGINFO;
529     act.sa_handler = GC_restart_handler;
530     if (sigaction(SIG_THR_RESTART, &act, NULL) != 0) {
531         ABORT("Cannot set SIG_THR_RESTART handler");
532     }
533
534     /* Inititialize suspend_handler_mask. It excludes SIG_THR_RESTART. */
535       if (sigfillset(&suspend_handler_mask) != 0) ABORT("sigfillset() failed");
536       GC_remove_allowed_signals(&suspend_handler_mask);
537       if (sigdelset(&suspend_handler_mask, SIG_THR_RESTART) != 0)
538           ABORT("sigdelset() failed");
539
540     /* Check for GC_RETRY_SIGNALS.      */
541       if (0 != GETENV("GC_RETRY_SIGNALS")) {
542           GC_retry_signals = TRUE;
543       }
544       if (0 != GETENV("GC_NO_RETRY_SIGNALS")) {
545           GC_retry_signals = FALSE;
546       }
547       if (GC_print_stats && GC_retry_signals) {
548           GC_log_printf("Will retry suspend signal if necessary.\n");
549       }
550 }
551
552 /* Added for cacao */
553 int GC_signum1()
554 {
555     return SIG_SUSPEND;
556 }
557
558 int GC_signum2()
559 {
560     return SIG_THR_RESTART;
561 }
562 /* cacao END */
563
564 #endif