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