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