Update Go library to last weekly.
[platform/upstream/gcc.git] / libgo / runtime / go-go.c
1 /* go-go.c -- the go function.
2
3    Copyright 2009 The Go Authors. All rights reserved.
4    Use of this source code is governed by a BSD-style
5    license that can be found in the LICENSE file.  */
6
7 #include <errno.h>
8 #include <limits.h>
9 #include <signal.h>
10 #include <stdint.h>
11 #include <stdlib.h>
12 #include <pthread.h>
13 #include <semaphore.h>
14
15 #include "config.h"
16 #include "go-assert.h"
17 #include "go-panic.h"
18 #include "go-alloc.h"
19 #include "runtime.h"
20 #include "arch.h"
21 #include "malloc.h"
22
23 #ifdef USING_SPLIT_STACK
24 /* FIXME: This is not declared anywhere.  */
25 extern void *__splitstack_find (void *, void *, size_t *, void **, void **,
26                                 void **);
27 #endif
28
29 /* We stop the threads by sending them the signal GO_SIG_STOP and we
30    start them by sending them the signal GO_SIG_START.  */
31
32 #define GO_SIG_START (SIGRTMIN + 1)
33 #define GO_SIG_STOP (SIGRTMIN + 2)
34
35 #ifndef SA_RESTART
36   #define SA_RESTART 0
37 #endif
38
39 /* A doubly linked list of the threads we have started.  */
40
41 struct __go_thread_id
42 {
43   /* Links.  */
44   struct __go_thread_id *prev;
45   struct __go_thread_id *next;
46   /* True if the thread ID has not yet been filled in.  */
47   _Bool tentative;
48   /* Thread ID.  */
49   pthread_t id;
50   /* Thread's M structure.  */
51   struct M *m;
52   /* If the thread ID has not been filled in, the function we are
53      running.  */
54   void (*pfn) (void *);
55   /* If the thread ID has not been filled in, the argument to the
56      function.  */
57   void *arg;
58 };
59
60 static struct __go_thread_id *__go_all_thread_ids;
61
62 /* A lock to control access to ALL_THREAD_IDS.  */
63
64 static pthread_mutex_t __go_thread_ids_lock = PTHREAD_MUTEX_INITIALIZER;
65
66 /* A semaphore used to wait until all the threads have stopped.  */
67
68 static sem_t __go_thread_ready_sem;
69
70 /* A signal set used to wait until garbage collection is complete.  */
71
72 static sigset_t __go_thread_wait_sigset;
73
74 /* Remove the current thread from the list of threads.  */
75
76 static void
77 remove_current_thread (void *dummy __attribute__ ((unused)))
78 {
79   struct __go_thread_id *list_entry;
80   MCache *mcache;
81   int i;
82   
83   list_entry = m->list_entry;
84   mcache = m->mcache;
85
86   i = pthread_mutex_lock (&__go_thread_ids_lock);
87   __go_assert (i == 0);
88
89   if (list_entry->prev != NULL)
90     list_entry->prev->next = list_entry->next;
91   else
92     __go_all_thread_ids = list_entry->next;
93   if (list_entry->next != NULL)
94     list_entry->next->prev = list_entry->prev;
95
96   /* This will lock runtime_mheap as needed.  */
97   runtime_MCache_ReleaseAll (mcache);
98
99   /* This should never deadlock--there shouldn't be any code that
100      holds the runtime_mheap lock when locking __go_thread_ids_lock.
101      We don't want to do this after releasing __go_thread_ids_lock
102      because it will mean that the garbage collector might run, and
103      the garbage collector does not try to lock runtime_mheap in all
104      cases since it knows it is running single-threaded.  */
105   runtime_lock (&runtime_mheap);
106   mstats.heap_alloc += mcache->local_alloc;
107   mstats.heap_objects += mcache->local_objects;
108   __builtin_memset (mcache, 0, sizeof (struct MCache));
109   runtime_FixAlloc_Free (&runtime_mheap.cachealloc, mcache);
110   runtime_unlock (&runtime_mheap);
111
112   /* As soon as we release this look, a GC could run.  Since this
113      thread is no longer on the list, the GC will not find our M
114      structure, so it could get freed at any time.  That means that
115      any code from here to thread exit must not assume that m is
116      valid.  */
117   m = NULL;
118
119   i = pthread_mutex_unlock (&__go_thread_ids_lock);
120   __go_assert (i == 0);
121
122   free (list_entry);
123 }
124
125 /* Start the thread.  */
126
127 static void *
128 start_go_thread (void *thread_arg)
129 {
130   struct M *newm = (struct M *) thread_arg;
131   void (*pfn) (void *);
132   void *arg;
133   struct __go_thread_id *list_entry;
134   int i;
135
136 #ifdef __rtems__
137   __wrap_rtems_task_variable_add ((void **) &m);
138   __wrap_rtems_task_variable_add ((void **) &__go_panic_defer);
139 #endif
140
141   m = newm;
142
143   pthread_cleanup_push (remove_current_thread, NULL);
144
145   list_entry = newm->list_entry;
146
147   pfn = list_entry->pfn;
148   arg = list_entry->arg;
149
150 #ifndef USING_SPLIT_STACK
151   /* If we don't support split stack, record the current stack as the
152      top of the stack.  There shouldn't be anything relevant to the
153      garbage collector above this point.  */
154   m->gc_sp = (void *) &arg;
155 #endif
156
157   /* Finish up the entry on the thread list.  */
158
159   i = pthread_mutex_lock (&__go_thread_ids_lock);
160   __go_assert (i == 0);
161
162   list_entry->id = pthread_self ();
163   list_entry->pfn = NULL;
164   list_entry->arg = NULL;
165   list_entry->tentative = 0;
166
167   i = pthread_mutex_unlock (&__go_thread_ids_lock);
168   __go_assert (i == 0);
169
170   (*pfn) (arg);
171
172   pthread_cleanup_pop (1);
173
174   return NULL;
175 }
176
177 /* The runtime.Goexit function.  */
178
179 void Goexit (void) asm ("libgo_runtime.runtime.Goexit");
180
181 void
182 Goexit (void)
183 {
184   pthread_exit (NULL);
185   abort ();
186 }
187
188 /* Count of threads created.  */
189
190 static volatile int mcount;
191
192 /* Implement the go statement.  */
193
194 void
195 __go_go (void (*pfn) (void*), void *arg)
196 {
197   int i;
198   pthread_attr_t attr;
199   struct M *newm;
200   struct __go_thread_id *list_entry;
201   pthread_t tid;
202
203   i = pthread_attr_init (&attr);
204   __go_assert (i == 0);
205   i = pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
206   __go_assert (i == 0);
207
208 #ifdef LINKER_SUPPORTS_SPLIT_STACK
209   /* The linker knows how to handle calls between code which uses
210      -fsplit-stack and code which does not.  That means that we can
211      run with a smaller stack and rely on the -fsplit-stack support to
212      save us.  The GNU/Linux glibc library won't let us have a very
213      small stack, but we make it as small as we can.  */
214 #ifndef PTHREAD_STACK_MIN
215 #define PTHREAD_STACK_MIN 8192
216 #endif
217   i = pthread_attr_setstacksize (&attr, PTHREAD_STACK_MIN);
218   __go_assert (i == 0);
219 #endif
220
221   newm = __go_alloc (sizeof (M));
222
223   list_entry = malloc (sizeof (struct __go_thread_id));
224   list_entry->prev = NULL;
225   list_entry->next = NULL;
226   list_entry->tentative = 1;
227   list_entry->m = newm;
228   list_entry->pfn = pfn;
229   list_entry->arg = arg;
230
231   newm->list_entry = list_entry;
232
233   newm->id = __sync_fetch_and_add (&mcount, 1);
234   newm->fastrand = 0x49f6428aUL + newm->id;
235
236   newm->mcache = runtime_allocmcache ();
237
238   /* Add the thread to the list of all threads, marked as tentative
239      since it is not yet ready to go.  */
240   i = pthread_mutex_lock (&__go_thread_ids_lock);
241   __go_assert (i == 0);
242
243   if (__go_all_thread_ids != NULL)
244     __go_all_thread_ids->prev = list_entry;
245   list_entry->next = __go_all_thread_ids;
246   __go_all_thread_ids = list_entry;
247
248   i = pthread_mutex_unlock (&__go_thread_ids_lock);
249   __go_assert (i == 0);
250
251   /* Start the thread.  */
252   i = pthread_create (&tid, &attr, start_go_thread, newm);
253   __go_assert (i == 0);
254
255   i = pthread_attr_destroy (&attr);
256   __go_assert (i == 0);
257 }
258
259 /* This is the signal handler for GO_SIG_START.  The garbage collector
260    will send this signal to a thread when it wants the thread to
261    start.  We don't have to actually do anything here, but we need a
262    signal handler since ignoring the signal will mean that the
263    sigsuspend will never see it.  */
264
265 static void
266 gc_start_handler (int sig __attribute__ ((unused)))
267 {
268 }
269
270 /* Tell the garbage collector that we are ready, and wait for the
271    garbage collector to tell us that it is done.  This may be called
272    by a signal handler, so it is restricted to using functions which
273    are async cancel safe.  */
274
275 static void
276 stop_for_gc (void)
277 {
278   int i;
279
280   /* Tell the garbage collector about our stack.  */
281 #ifdef USING_SPLIT_STACK
282   m->gc_sp = __splitstack_find (NULL, NULL, &m->gc_len,
283                                 &m->gc_next_segment, &m->gc_next_sp,
284                                 &m->gc_initial_sp);
285 #else
286   {
287     uintptr_t top = (uintptr_t) m->gc_sp;
288     uintptr_t bottom = (uintptr_t) &top;
289     if (top < bottom)
290       {
291         m->gc_next_sp = m->gc_sp;
292         m->gc_len = bottom - top;
293       }
294     else
295       {
296         m->gc_next_sp = (void *) bottom;
297         m->gc_len = top - bottom;
298       }
299   }
300 #endif
301
302   /* FIXME: Perhaps we should just move __go_panic_defer into M.  */
303   m->gc_panic_defer = __go_panic_defer;
304
305   /* Tell the garbage collector that we are ready by posting to the
306      semaphore.  */
307   i = sem_post (&__go_thread_ready_sem);
308   __go_assert (i == 0);
309
310   /* Wait for the garbage collector to tell us to continue.  */
311   sigsuspend (&__go_thread_wait_sigset);
312 }
313
314 /* This is the signal handler for GO_SIG_STOP.  The garbage collector
315    will send this signal to a thread when it wants the thread to
316    stop.  */
317
318 static void
319 gc_stop_handler (int sig __attribute__ ((unused)))
320 {
321   struct M *pm = m;
322
323   if (__sync_bool_compare_and_swap (&pm->holds_finlock, 1, 1))
324     {
325       /* We can't interrupt the thread while it holds the finalizer
326          lock.  Otherwise we can get into a deadlock when mark calls
327          runtime_walkfintab.  */
328       __sync_bool_compare_and_swap (&pm->gcing_for_finlock, 0, 1);
329       return;
330     }
331
332   if (__sync_bool_compare_and_swap (&pm->mallocing, 1, 1))
333     {
334       /* m->mallocing was already non-zero.  We can't interrupt the
335          thread while it is running an malloc.  Instead, tell it to
336          call back to us when done.  */
337       __sync_bool_compare_and_swap (&pm->gcing, 0, 1);
338       return;
339     }
340
341   if (__sync_bool_compare_and_swap (&pm->nomemprof, 1, 1))
342     {
343       /* Similarly, we can't interrupt the thread while it is building
344          profiling information.  Otherwise we can get into a deadlock
345          when sweepspan calls MProf_Free.  */
346       __sync_bool_compare_and_swap (&pm->gcing_for_prof, 0, 1);
347       return;
348     }
349
350   stop_for_gc ();
351 }
352
353 /* This is called by malloc when it gets a signal during the malloc
354    call itself.  */
355
356 int
357 __go_run_goroutine_gc (int r)
358 {
359   /* Force callee-saved registers to be saved on the stack.  This is
360      not needed if we are invoked from the signal handler, but it is
361      needed if we are called directly, since otherwise we might miss
362      something that a function somewhere up the call stack is holding
363      in a register.  */
364   __builtin_unwind_init ();
365
366   stop_for_gc ();
367
368   /* This avoids tail recursion, to make sure that the saved registers
369      are on the stack.  */
370   return r;
371 }
372
373 /* Stop all the other threads for garbage collection.  */
374
375 void
376 runtime_stoptheworld (void)
377 {
378   int i;
379   pthread_t me;
380   int c;
381   struct __go_thread_id *p;
382
383   i = pthread_mutex_lock (&__go_thread_ids_lock);
384   __go_assert (i == 0);
385
386   me = pthread_self ();
387   c = 0;
388   p = __go_all_thread_ids;
389   while (p != NULL)
390     {
391       if (p->tentative || pthread_equal (me, p->id))
392         p = p->next;
393       else
394         {
395           i = pthread_kill (p->id, GO_SIG_STOP);
396           if (i == 0)
397             {
398               ++c;
399               p = p->next;
400             }
401           else if (i == ESRCH)
402             {
403               struct __go_thread_id *next;
404
405               /* This thread died somehow.  Remove it from the
406                  list.  */
407               next = p->next;
408               if (p->prev != NULL)
409                 p->prev->next = next;
410               else
411                 __go_all_thread_ids = next;
412               if (next != NULL)
413                 next->prev = p->prev;
414               free (p);
415               p = next;
416             }
417           else
418             abort ();
419         }
420     }
421
422   /* Wait for each thread to receive the signal and post to the
423      semaphore.  If a thread receives the signal but contrives to die
424      before it posts to the semaphore, then we will hang forever
425      here.  */
426
427   while (c > 0)
428     {
429       i = sem_wait (&__go_thread_ready_sem);
430       if (i < 0 && errno == EINTR)
431         continue;
432       __go_assert (i == 0);
433       --c;
434     }
435
436   /* The gc_panic_defer field should now be set for all M's except the
437      one in this thread.  Set this one now.  */
438   m->gc_panic_defer = __go_panic_defer;
439
440   /* Leave with __go_thread_ids_lock held.  */
441 }
442
443 /* Scan all the stacks for garbage collection.  This should be called
444    with __go_thread_ids_lock held.  */
445
446 void
447 __go_scanstacks (void (*scan) (byte *, int64))
448 {
449   pthread_t me;
450   struct __go_thread_id *p;
451
452   /* Make sure all the registers for this thread are on the stack.  */
453   __builtin_unwind_init ();
454
455   me = pthread_self ();
456   for (p = __go_all_thread_ids; p != NULL; p = p->next)
457     {
458       if (p->tentative)
459         {
460           /* The goroutine function and argument can be allocated on
461              the heap, so we have to scan them for a thread that has
462              not yet started.  */
463           scan ((void *) &p->pfn, sizeof (void *));
464           scan ((void *) &p->arg, sizeof (void *));
465           scan ((void *) &p->m, sizeof (void *));
466           continue;
467         }
468
469 #ifdef USING_SPLIT_STACK
470
471       void *sp;
472       size_t len;
473       void *next_segment;
474       void *next_sp;
475       void *initial_sp;
476
477       if (pthread_equal (me, p->id))
478         {
479           next_segment = NULL;
480           next_sp = NULL;
481           initial_sp = NULL;
482           sp = __splitstack_find (NULL, NULL, &len, &next_segment,
483                                   &next_sp, &initial_sp);
484         }
485       else
486         {
487           sp = p->m->gc_sp;
488           len = p->m->gc_len;
489           next_segment = p->m->gc_next_segment;
490           next_sp = p->m->gc_next_sp;
491           initial_sp = p->m->gc_initial_sp;
492         }
493
494       while (sp != NULL)
495         {
496           scan (sp, len);
497           sp = __splitstack_find (next_segment, next_sp, &len,
498                                   &next_segment, &next_sp, &initial_sp);
499         }
500
501 #else /* !defined(USING_SPLIT_STACK) */
502
503       if (pthread_equal (me, p->id))
504         {
505           uintptr_t top = (uintptr_t) m->gc_sp;
506           uintptr_t bottom = (uintptr_t) &top;
507           if (top < bottom)
508             scan (m->gc_sp, bottom - top);
509           else
510             scan ((void *) bottom, top - bottom);
511         }
512       else
513         {
514           scan (p->m->gc_next_sp, p->m->gc_len);
515         }
516         
517 #endif /* !defined(USING_SPLIT_STACK) */
518
519       /* Also scan the M structure while we're at it.  */
520
521       scan ((void *) &p->m, sizeof (void *));
522     }
523 }
524
525 /* Release all the memory caches.  This is called with
526    __go_thread_ids_lock held.  */
527
528 void
529 __go_stealcache (void)
530 {
531   struct __go_thread_id *p;
532
533   for (p = __go_all_thread_ids; p != NULL; p = p->next)
534     runtime_MCache_ReleaseAll (p->m->mcache);
535 }
536
537 /* Gather memory cache statistics.  This is called with
538    __go_thread_ids_lock held.  */
539
540 void
541 __go_cachestats (void)
542 {
543   struct __go_thread_id *p;
544
545   for (p = __go_all_thread_ids; p != NULL; p = p->next)
546     {
547       MCache *c;
548       int i;
549
550       runtime_purgecachedstats(p->m);
551       c = p->m->mcache;
552       for (i = 0; i < NumSizeClasses; ++i)
553         {
554           mstats.by_size[i].nmalloc += c->local_by_size[i].nmalloc;
555           c->local_by_size[i].nmalloc = 0;
556           mstats.by_size[i].nfree += c->local_by_size[i].nfree;
557           c->local_by_size[i].nfree = 0;
558         }
559     }
560 }
561
562 /* Start the other threads after garbage collection.  */
563
564 void
565 runtime_starttheworld (bool extra __attribute__ ((unused)))
566 {
567   int i;
568   pthread_t me;
569   struct __go_thread_id *p;
570
571   /* Here __go_thread_ids_lock should be held.  */
572
573   me = pthread_self ();
574   p = __go_all_thread_ids;
575   while (p != NULL)
576     {
577       if (p->tentative || pthread_equal (me, p->id))
578         p = p->next;
579       else
580         {
581           i = pthread_kill (p->id, GO_SIG_START);
582           if (i == 0)
583             p = p->next;
584           else
585             abort ();
586         }
587     }
588
589   i = pthread_mutex_unlock (&__go_thread_ids_lock);
590   __go_assert (i == 0);
591 }
592
593 /* Initialize the interaction between goroutines and the garbage
594    collector.  */
595
596 void
597 __go_gc_goroutine_init (void *sp __attribute__ ((unused)))
598 {
599   struct __go_thread_id *list_entry;
600   int i;
601   sigset_t sset;
602   struct sigaction act;
603
604   /* Add the initial thread to the list of all threads.  */
605
606   list_entry = malloc (sizeof (struct __go_thread_id));
607   list_entry->prev = NULL;
608   list_entry->next = NULL;
609   list_entry->tentative = 0;
610   list_entry->id = pthread_self ();
611   list_entry->m = m;
612   list_entry->pfn = NULL;
613   list_entry->arg = NULL;
614   __go_all_thread_ids = list_entry;
615
616   /* Initialize the semaphore which signals when threads are ready for
617      GC.  */
618
619   i = sem_init (&__go_thread_ready_sem, 0, 0);
620   __go_assert (i == 0);
621
622   /* Fetch the current signal mask.  */
623
624   i = sigemptyset (&sset);
625   __go_assert (i == 0);
626   i = sigprocmask (SIG_BLOCK, NULL, &sset);
627   __go_assert (i == 0);
628
629   /* Make sure that GO_SIG_START is not blocked and GO_SIG_STOP is
630      blocked, and save that set for use with later calls to sigsuspend
631      while waiting for GC to complete.  */
632
633   i = sigdelset (&sset, GO_SIG_START);
634   __go_assert (i == 0);
635   i = sigaddset (&sset, GO_SIG_STOP);
636   __go_assert (i == 0);
637   __go_thread_wait_sigset = sset;
638
639   /* Block SIG_SET_START and unblock SIG_SET_STOP, and use that for
640      the process signal mask.  */
641
642   i = sigaddset (&sset, GO_SIG_START);
643   __go_assert (i == 0);
644   i = sigdelset (&sset, GO_SIG_STOP);
645   __go_assert (i == 0);
646   i = sigprocmask (SIG_SETMASK, &sset, NULL);
647   __go_assert (i == 0);
648
649   /* Install the signal handlers.  */
650   memset (&act, 0, sizeof act);
651   i = sigemptyset (&act.sa_mask);
652   __go_assert (i == 0);
653
654   act.sa_handler = gc_start_handler;
655   act.sa_flags = SA_RESTART;
656   i = sigaction (GO_SIG_START, &act, NULL);
657   __go_assert (i == 0);
658
659   /* We could consider using an alternate signal stack for this.  The
660      function does not use much stack space, so it may be OK.  */
661   act.sa_handler = gc_stop_handler;
662   i = sigaction (GO_SIG_STOP, &act, NULL);
663   __go_assert (i == 0);
664
665 #ifndef USING_SPLIT_STACK
666   /* If we don't support split stack, record the current stack as the
667      top of the stack.  */
668   m->gc_sp = sp;
669 #endif
670 }