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