Back to index

lightning-sunbird  0.9+nobinonly
solaris_threads.c
Go to the documentation of this file.
00001 /* 
00002  * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
00003  *
00004  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
00005  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
00006  *
00007  * Permission is hereby granted to use or copy this program
00008  * for any purpose,  provided the above notices are retained on all copies.
00009  * Permission to modify the code and to distribute modified code is granted,
00010  * provided the above notices are retained, and a notice that the code was
00011  * modified is included with the above copyright notice.
00012  */
00013 /*
00014  * Support code for Solaris threads.  Provides functionality we wish Sun
00015  * had provided.  Relies on some information we probably shouldn't rely on.
00016  */
00017 /* Boehm, September 14, 1994 4:44 pm PDT */
00018 
00019 # if defined(SOLARIS_THREADS)
00020 
00021 # include "gc_priv.h"
00022 # include "solaris_threads.h"
00023 # include <thread.h>
00024 # include <synch.h>
00025 # include <signal.h>
00026 # include <fcntl.h>
00027 # include <sys/types.h>
00028 # include <sys/mman.h>
00029 # include <sys/time.h>
00030 # include <sys/resource.h>
00031 # include <sys/stat.h>
00032 # include <sys/syscall.h>
00033 # include <sys/procfs.h>
00034 # include <sys/lwp.h>
00035 # include <sys/reg.h>
00036 # define _CLASSIC_XOPEN_TYPES
00037 # include <unistd.h>
00038 # include <errno.h>
00039 
00040 /*
00041  * This is the default size of the LWP arrays. If there are more LWPs
00042  * than this when a stop-the-world GC happens, set_max_lwps will be
00043  * called to cope.
00044  * This must be higher than the number of LWPs at startup time.
00045  * The threads library creates a thread early on, so the min. is 3
00046  */
00047 # define DEFAULT_MAX_LWPS   4
00048 
00049 #undef thr_join
00050 #undef thr_create
00051 #undef thr_suspend
00052 #undef thr_continue
00053 
00054 cond_t GC_prom_join_cv;            /* Broadcast when any thread terminates   */
00055 cond_t GC_create_cv;        /* Signalled when a new undetached */
00056                             /* thread starts.                  */
00057                             
00058 
00059 #ifdef MMAP_STACKS
00060 static int GC_zfd;
00061 #endif /* MMAP_STACKS */
00062 
00063 /* We use the allocation lock to protect thread-related data structures. */
00064 
00065 /* We stop the world using /proc primitives.  This makes some  */
00066 /* minimal assumptions about the threads implementation.       */
00067 /* We don't play by the rules, since the rules make this       */
00068 /* impossible (as of Solaris 2.3).  Also note that as of       */
00069 /* Solaris 2.3 the various thread and lwp suspension           */
00070 /* primitives failed to stop threads by the time the request   */
00071 /* is completed.                                        */
00072 
00073 
00074 static sigset_t old_mask;
00075 
00076 /* Sleep for n milliseconds, n < 1000     */
00077 void GC_msec_sleep(int n)
00078 {
00079     struct timespec ts;
00080                             
00081     ts.tv_sec = 0;
00082     ts.tv_nsec = 1000000*n;
00083     if (syscall(SYS_nanosleep, &ts, 0) < 0) {
00084        ABORT("nanosleep failed");
00085     }
00086 }
00087 /* Turn off preemption;  gross but effective.           */
00088 /* Caller has allocation lock.                          */
00089 /* Actually this is not needed under Solaris 2.3 and    */
00090 /* 2.4, but hopefully that'll change.                   */
00091 void preempt_off()
00092 {
00093     sigset_t set;
00094 
00095     (void)sigfillset(&set);
00096     sigdelset(&set, SIGABRT);
00097     syscall(SYS_sigprocmask, SIG_SETMASK, &set, &old_mask);
00098 }
00099 
00100 void preempt_on()
00101 {
00102     syscall(SYS_sigprocmask, SIG_SETMASK, &old_mask, NULL);
00103 }
00104 
00105 int GC_main_proc_fd = -1;
00106 
00107 
00108 struct lwp_cache_entry {
00109     lwpid_t lc_id;
00110     int lc_descr;    /* /proc file descriptor.   */
00111 }  GC_lwp_cache_default[DEFAULT_MAX_LWPS];
00112 
00113 static int max_lwps = DEFAULT_MAX_LWPS;
00114 static struct lwp_cache_entry *GC_lwp_cache = GC_lwp_cache_default;
00115 
00116 static prgregset_t GC_lwp_registers_default[DEFAULT_MAX_LWPS];
00117 static prgregset_t *GC_lwp_registers = GC_lwp_registers_default;
00118 
00119 /* Return a file descriptor for the /proc entry corresponding  */
00120 /* to the given lwp.  The file descriptor may be stale if the  */
00121 /* lwp exited and a new one was forked.                        */
00122 static int open_lwp(lwpid_t id)
00123 {
00124     int result;
00125     static int next_victim = 0;
00126     register int i;
00127     
00128     for (i = 0; i < max_lwps; i++) {
00129        if (GC_lwp_cache[i].lc_id == id) return(GC_lwp_cache[i].lc_descr);
00130     }
00131     result = syscall(SYS_ioctl, GC_main_proc_fd, PIOCOPENLWP, &id);
00132     /*
00133      * If PIOCOPENLWP fails, try closing fds in the cache until it succeeds.
00134      */
00135     if (result < 0 && errno == EMFILE) {
00136            for (i = 0; i < max_lwps; i++) {
00137               if (GC_lwp_cache[i].lc_id != 0) {
00138                      (void)syscall(SYS_close, GC_lwp_cache[i].lc_descr);
00139                      result = syscall(SYS_ioctl, GC_main_proc_fd, PIOCOPENLWP, &id);
00140                      if (result >= 0 || (result < 0 && errno != EMFILE))
00141                             break;
00142               }
00143            }
00144     }
00145     if (result < 0) {
00146        if (errno == EMFILE) {
00147               ABORT("Too many open files");
00148        }
00149         return(-1) /* exited? */;
00150     }
00151     if (GC_lwp_cache[next_victim].lc_id != 0)
00152         (void)syscall(SYS_close, GC_lwp_cache[next_victim].lc_descr);
00153     GC_lwp_cache[next_victim].lc_id = id;
00154     GC_lwp_cache[next_victim].lc_descr = result;
00155     if (++next_victim >= max_lwps)
00156        next_victim = 0;
00157     return(result);
00158 }
00159 
00160 static void uncache_lwp(lwpid_t id)
00161 {
00162     register int i;
00163     
00164     for (i = 0; i < max_lwps; i++) {
00165        if (GC_lwp_cache[i].lc_id == id) {
00166            (void)syscall(SYS_close, GC_lwp_cache[id].lc_descr);
00167            GC_lwp_cache[i].lc_id = 0;
00168            break;
00169        }
00170     }
00171 }
00172        /* Sequence of current lwp ids     */
00173 static lwpid_t GC_current_ids_default[DEFAULT_MAX_LWPS + 1];
00174 static lwpid_t *GC_current_ids = GC_current_ids_default;
00175 
00176        /* Temporary used below (can be big if large number of LWPs) */
00177 static lwpid_t last_ids_default[DEFAULT_MAX_LWPS + 1];
00178 static lwpid_t *last_ids = last_ids_default;
00179 
00180 
00181 #define ROUNDUP(n)    WORDS_TO_BYTES(ROUNDED_UP_WORDS(n))
00182 
00183 static void set_max_lwps(GC_word n)
00184 {
00185     char *mem;
00186     char *oldmem;
00187     int required_bytes = ROUNDUP(n * sizeof(struct lwp_cache_entry))
00188        + ROUNDUP(n * sizeof(prgregset_t))
00189        + ROUNDUP((n + 1) * sizeof(lwpid_t))
00190        + ROUNDUP((n + 1) * sizeof(lwpid_t));
00191 
00192     GC_expand_hp_inner(divHBLKSZ((word)required_bytes));
00193     oldmem = mem = GC_scratch_alloc(required_bytes);
00194     if (0 == mem) ABORT("No space for lwp data structures");
00195 
00196     /*
00197      * We can either flush the old lwp cache or copy it over. Do the latter.
00198      */
00199     memcpy(mem, GC_lwp_cache, max_lwps * sizeof(struct lwp_cache_entry));
00200     GC_lwp_cache = (struct lwp_cache_entry*)mem;
00201     mem += ROUNDUP(n * sizeof(struct lwp_cache_entry));
00202 
00203     BZERO(GC_lwp_registers, max_lwps * sizeof(GC_lwp_registers[0]));
00204     GC_lwp_registers = (prgregset_t *)mem;
00205     mem += ROUNDUP(n * sizeof(prgregset_t));
00206 
00207 
00208     GC_current_ids = (lwpid_t *)mem;
00209     mem += ROUNDUP((n + 1) * sizeof(lwpid_t));
00210 
00211     last_ids = (lwpid_t *)mem;
00212     mem += ROUNDUP((n + 1)* sizeof(lwpid_t));
00213 
00214     if (mem > oldmem + required_bytes)
00215        ABORT("set_max_lwps buffer overflow");
00216 
00217     max_lwps = n;
00218 }
00219 
00220 
00221 /* Stop all lwps in process.  Assumes preemption is off.       */
00222 /* Caller has allocation lock (and any other locks he may      */
00223 /* need).                                               */
00224 static void stop_all_lwps()
00225 {
00226     int lwp_fd;
00227     char buf[30];
00228     prstatus_t status;
00229     register int i;
00230     GC_bool changed;
00231     lwpid_t me = _lwp_self();
00232 
00233     if (GC_main_proc_fd == -1) {
00234        sprintf(buf, "/proc/%d", getpid());
00235        GC_main_proc_fd = syscall(SYS_open, buf, O_RDONLY);
00236         if (GC_main_proc_fd < 0) {
00237               if (errno == EMFILE)
00238                      ABORT("/proc open failed: too many open files");
00239               GC_printf1("/proc open failed: errno %d", errno);
00240               abort();
00241         }
00242     }
00243     BZERO(GC_lwp_registers, sizeof (prgregset_t) * max_lwps);
00244     for (i = 0; i < max_lwps; i++)
00245        last_ids[i] = 0;
00246     for (;;) {
00247     if (syscall(SYS_ioctl, GC_main_proc_fd, PIOCSTATUS, &status) < 0)
00248        ABORT("Main PIOCSTATUS failed");
00249        if (status.pr_nlwp < 1)
00250               ABORT("Invalid number of lwps returned by PIOCSTATUS");
00251        if (status.pr_nlwp >= max_lwps) {
00252               set_max_lwps(status.pr_nlwp*2 + 10);
00253               /*
00254                * The data in the old GC_current_ids and
00255                * GC_lwp_registers has been trashed. Cleaning out last_ids
00256                * will make sure every LWP gets re-examined.
00257                */
00258               for (i = 0; i < max_lwps; i++)
00259                      last_ids[i] = 0;
00260               continue;
00261     }
00262         if (syscall(SYS_ioctl, GC_main_proc_fd, PIOCLWPIDS, GC_current_ids) < 0)
00263             ABORT("PIOCLWPIDS failed");
00264         changed = FALSE;
00265         for (i = 0; GC_current_ids[i] != 0 && i < max_lwps; i++) {
00266             if (GC_current_ids[i] != last_ids[i]) {
00267                 changed = TRUE;
00268                 if (GC_current_ids[i] != me) {
00269                   /* PIOCSTOP doesn't work without a writable         */
00270                   /* descriptor.  And that makes the process          */
00271                   /* undebuggable.                             */
00272                     if (_lwp_suspend(GC_current_ids[i]) < 0) {
00273                         /* Could happen if the lwp exited */
00274                         uncache_lwp(GC_current_ids[i]);
00275                         GC_current_ids[i] = me; /* ignore */
00276                     }
00277                 }
00278             }
00279         }
00280         /*
00281          * In the unlikely event something does a fork between the
00282         * PIOCSTATUS and the PIOCLWPIDS. 
00283          */
00284         if (i >= max_lwps)
00285               continue;
00286         /* All lwps in GC_current_ids != me have been suspended.  Note       */
00287         /* that _lwp_suspend is idempotent.                           */
00288         for (i = 0; GC_current_ids[i] != 0; i++) {
00289             if (GC_current_ids[i] != last_ids[i]) {
00290                 if (GC_current_ids[i] != me) {
00291                     lwp_fd = open_lwp(GC_current_ids[i]);
00292                   if (lwp_fd == -1)
00293                   {
00294                          GC_current_ids[i] = me;
00295                          continue;
00296                   }
00297                   /* LWP should be stopped.  Empirically it sometimes */
00298                   /* isn't, and more frequently the PR_STOPPED flag   */
00299                   /* is not set.  Wait for PR_STOPPED.         */
00300                     if (syscall(SYS_ioctl, lwp_fd,
00301                                 PIOCSTATUS, &status) < 0) {
00302                      /* Possible if the descriptor was stale, or */
00303                      /* we encountered the 2.3 _lwp_suspend bug. */
00304                      uncache_lwp(GC_current_ids[i]);
00305                         GC_current_ids[i] = me; /* handle next time. */
00306                     } else {
00307                         while (!(status.pr_flags & PR_STOPPED)) {
00308                             GC_msec_sleep(1);
00309                          if (syscall(SYS_ioctl, lwp_fd,
00310                                    PIOCSTATUS, &status) < 0) {
00311                                    ABORT("Repeated PIOCSTATUS failed");
00312                          }
00313                          if (status.pr_flags & PR_STOPPED) break;
00314                          
00315                          GC_msec_sleep(20);
00316                          if (syscall(SYS_ioctl, lwp_fd,
00317                                    PIOCSTATUS, &status) < 0) {
00318                                    ABORT("Repeated PIOCSTATUS failed");
00319                          }
00320                         }
00321                         if (status.pr_who !=  GC_current_ids[i]) {
00322                             /* can happen if thread was on death row */
00323                             uncache_lwp(GC_current_ids[i]);
00324                             GC_current_ids[i] = me; /* handle next time. */
00325                             continue;     
00326                         }
00327                         /* Save registers where collector can */
00328                      /* find them.                 */
00329                          BCOPY(status.pr_reg, GC_lwp_registers[i],
00330                               sizeof (prgregset_t));
00331                     }
00332                 }
00333             }
00334         }
00335         if (!changed) break;
00336         for (i = 0; i < max_lwps; i++) last_ids[i] = GC_current_ids[i];
00337     }
00338 }
00339 
00340 /* Restart all lwps in process.  Assumes preemption is off.    */
00341 static void restart_all_lwps()
00342 {
00343     int lwp_fd;
00344     register int i;
00345     GC_bool changed;
00346     lwpid_t me = _lwp_self();
00347 #   define PARANOID
00348 
00349     for (i = 0; GC_current_ids[i] != 0; i++) {
00350 #      ifdef PARANOID
00351          if (GC_current_ids[i] != me) {
00352            int lwp_fd = open_lwp(GC_current_ids[i]);
00353            prstatus_t status;
00354            
00355            if (lwp_fd < 0) ABORT("open_lwp failed");
00356            if (syscall(SYS_ioctl, lwp_fd,
00357                      PIOCSTATUS, &status) < 0) {
00358                 ABORT("PIOCSTATUS failed in restart_all_lwps");
00359            }
00360            if (memcmp(status.pr_reg, GC_lwp_registers[i],
00361                      sizeof (prgregset_t)) != 0) {
00362                   int j;
00363 
00364                   for(j = 0; j < NGREG; j++)
00365                   {
00366                          GC_printf3("%i: %x -> %x\n", j,
00367                                    GC_lwp_registers[i][j],
00368                                    status.pr_reg[j]);
00369                   }
00370               ABORT("Register contents changed");
00371            }
00372            if (!status.pr_flags & PR_STOPPED) {
00373               ABORT("lwp no longer stopped");
00374            }
00375 #ifdef SPARC
00376            {
00377                   gwindows_t windows;
00378              if (syscall(SYS_ioctl, lwp_fd,
00379                      PIOCGWIN, &windows) < 0) {
00380                 ABORT("PIOCSTATUS failed in restart_all_lwps");
00381              }
00382              if (windows.wbcnt > 0) ABORT("unsaved register windows");
00383            }
00384 #endif
00385          }
00386 #      endif /* PARANOID */
00387        if (GC_current_ids[i] == me) continue;
00388         if (_lwp_continue(GC_current_ids[i]) < 0) {
00389             ABORT("Failed to restart lwp");
00390         }
00391     }
00392     if (i >= max_lwps) ABORT("Too many lwps");
00393 }
00394 
00395 GC_bool GC_multithreaded = 0;
00396 
00397 void GC_stop_world()
00398 {
00399     preempt_off();
00400     if (GC_multithreaded)
00401         stop_all_lwps();
00402 }
00403 
00404 void GC_start_world()
00405 {
00406     if (GC_multithreaded)
00407         restart_all_lwps();
00408     preempt_on();
00409 }
00410 
00411 void GC_thr_init(void);
00412 
00413 GC_bool GC_thr_initialized = FALSE;
00414 
00415 size_t GC_min_stack_sz;
00416 
00417 size_t GC_page_sz;
00418 
00419 /*
00420  * stack_head is stored at the top of free stacks
00421  */
00422 struct stack_head {
00423        struct stack_head    *next;
00424        ptr_t                base;
00425        thread_t             owner;
00426 };
00427 
00428 # define N_FREE_LISTS 25
00429 struct stack_head *GC_stack_free_lists[N_FREE_LISTS] = { 0 };
00430               /* GC_stack_free_lists[i] is free list for stacks of    */
00431               /* size GC_min_stack_sz*2**i.                           */
00432               /* Free lists are linked through stack_head stored      */                   /* at top of stack.                              */
00433 
00434 /* Return a stack of size at least *stack_size.  *stack_size is       */
00435 /* replaced by the actual stack size.                          */
00436 /* Caller holds allocation lock.                        */
00437 ptr_t GC_stack_alloc(size_t * stack_size)
00438 {
00439     register size_t requested_sz = *stack_size;
00440     register size_t search_sz = GC_min_stack_sz;
00441     register int index = 0; /* = log2(search_sz/GC_min_stack_sz) */
00442     register ptr_t base;
00443     register struct stack_head *result;
00444     
00445     while (search_sz < requested_sz) {
00446         search_sz *= 2;
00447         index++;
00448     }
00449     if ((result = GC_stack_free_lists[index]) == 0
00450         && (result = GC_stack_free_lists[index+1]) != 0) {
00451         /* Try next size up. */
00452         search_sz *= 2; index++;
00453     }
00454     if (result != 0) {
00455         base =  GC_stack_free_lists[index]->base;
00456         GC_stack_free_lists[index] = GC_stack_free_lists[index]->next;
00457     } else {
00458 #ifdef MMAP_STACKS
00459         base = (ptr_t)mmap(0, search_sz + GC_page_sz,
00460                           PROT_READ|PROT_WRITE, MAP_PRIVATE |MAP_NORESERVE,
00461                           GC_zfd, 0);
00462        if (base == (ptr_t)-1)
00463        {
00464               *stack_size = 0;
00465               return NULL;
00466        }
00467 
00468        mprotect(base, GC_page_sz, PROT_NONE);
00469        /* Should this use divHBLKSZ(search_sz + GC_page_sz) ? -- cf */
00470        GC_is_fresh((struct hblk *)base, divHBLKSZ(search_sz));
00471        base += GC_page_sz;
00472 
00473 #else
00474         base = (ptr_t) GC_scratch_alloc(search_sz + 2*GC_page_sz);
00475        if (base == NULL)
00476        {
00477               *stack_size = 0;
00478               return NULL;
00479        }
00480 
00481         base = (ptr_t)(((word)base + GC_page_sz) & ~(GC_page_sz - 1));
00482         /* Protect hottest page to detect overflow. */
00483 #      ifdef SOLARIS23_MPROTECT_BUG_FIXED
00484             mprotect(base, GC_page_sz, PROT_NONE);
00485 #      endif
00486         GC_is_fresh((struct hblk *)base, divHBLKSZ(search_sz));
00487 
00488         base += GC_page_sz;
00489 #endif
00490     }
00491     *stack_size = search_sz;
00492     return(base);
00493 }
00494 
00495 /* Caller holds  allocationlock.                               */
00496 void GC_stack_free(ptr_t stack, size_t size)
00497 {
00498     register int index = 0;
00499     register size_t search_sz = GC_min_stack_sz;
00500     register struct stack_head *head;
00501     
00502 #ifdef MMAP_STACKS
00503     /* Zero pointers */
00504     mmap(stack, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_NORESERVE|MAP_FIXED,
00505         GC_zfd, 0);
00506 #endif
00507     while (search_sz < size) {
00508         search_sz *= 2;
00509         index++;
00510     }
00511     if (search_sz != size) ABORT("Bad stack size");
00512 
00513     head = (struct stack_head *)(stack + search_sz - sizeof(struct stack_head));
00514     head->next = GC_stack_free_lists[index];
00515     head->base = stack;
00516     GC_stack_free_lists[index] = head;
00517 }
00518 
00519 void GC_my_stack_limits();
00520 
00521 /* Notify virtual dirty bit implementation that known empty parts of  */
00522 /* stacks do not contain useful data.                                 */ 
00523 /* Caller holds allocation lock.                               */
00524 void GC_old_stacks_are_fresh()
00525 {
00526 /* No point in doing this for MMAP stacks - and pointers are zero'd out */
00527 /* by the mmap in GC_stack_free */
00528 #ifndef MMAP_STACKS
00529     register int i;
00530     register struct stack_head *s;
00531     register ptr_t p;
00532     register size_t sz;
00533     register struct hblk * h;
00534     int dummy;
00535     
00536     for (i = 0, sz= GC_min_stack_sz; i < N_FREE_LISTS;
00537          i++, sz *= 2) {
00538          for (s = GC_stack_free_lists[i]; s != 0; s = s->next) {
00539              p = s->base;
00540              h = (struct hblk *)(((word)p + HBLKSIZE-1) & ~(HBLKSIZE-1));
00541              if ((ptr_t)h == p) {
00542                  GC_is_fresh((struct hblk *)p, divHBLKSZ(sz));
00543              } else {
00544                  GC_is_fresh((struct hblk *)p, divHBLKSZ(sz) - 1);
00545                  BZERO(p, (ptr_t)h - p);
00546              }
00547          }
00548     }
00549 #endif /* MMAP_STACKS */
00550     GC_my_stack_limits();
00551 }
00552 
00553 /* The set of all known threads.  We intercept thread creation and    */
00554 /* joins.  We never actually create detached threads.  We allocate all       */
00555 /* new thread stacks ourselves.  These allow us to maintain this      */
00556 /* data structure.                                             */
00557 
00558 # define THREAD_TABLE_SZ 128       /* Must be power of 2       */
00559 volatile GC_thread GC_threads[THREAD_TABLE_SZ];
00560 
00561 /* Add a thread to GC_threads.  We assume it wasn't already there.    */
00562 /* Caller holds allocation lock.                               */
00563 GC_thread GC_new_thread(thread_t id)
00564 {
00565     int hv = ((word)id) % THREAD_TABLE_SZ;
00566     GC_thread result;
00567     static struct GC_Thread_Rep first_thread;
00568     static GC_bool first_thread_used = FALSE;
00569     
00570     if (!first_thread_used) {
00571        result = &first_thread;
00572        first_thread_used = TRUE;
00573        /* Dont acquire allocation lock, since we may already hold it. */
00574     } else {
00575         result = (struct GC_Thread_Rep *)
00576                GC_generic_malloc_inner(sizeof(struct GC_Thread_Rep), NORMAL);
00577     }
00578     if (result == 0) return(0);
00579     result -> id = id;
00580     result -> next = GC_threads[hv];
00581     GC_threads[hv] = result;
00582     /* result -> finished = 0; */
00583     (void) cond_init(&(result->join_cv), USYNC_THREAD, 0);
00584     return(result);
00585 }
00586 
00587 /* Delete a thread from GC_threads.  We assume it is there.    */
00588 /* (The code intentionally traps if it wasn't.)                */
00589 /* Caller holds allocation lock.                        */
00590 void GC_delete_thread(thread_t id)
00591 {
00592     int hv = ((word)id) % THREAD_TABLE_SZ;
00593     register GC_thread p = GC_threads[hv];
00594     register GC_thread prev = 0;
00595     
00596     while (p -> id != id) {
00597         prev = p;
00598         p = p -> next;
00599     }
00600     if (prev == 0) {
00601         GC_threads[hv] = p -> next;
00602     } else {
00603         prev -> next = p -> next;
00604     }
00605 }
00606 
00607 /* Return the GC_thread correpsonding to a given thread_t.     */
00608 /* Returns 0 if it's not there.                                */
00609 /* Caller holds  allocation lock.                       */
00610 GC_thread GC_lookup_thread(thread_t id)
00611 {
00612     int hv = ((word)id) % THREAD_TABLE_SZ;
00613     register GC_thread p = GC_threads[hv];
00614     
00615     while (p != 0 && p -> id != id) p = p -> next;
00616     return(p);
00617 }
00618 
00619 /* Notify dirty bit implementation of unused parts of my stack. */
00620 /* Caller holds allocation lock.                        */
00621 void GC_my_stack_limits()
00622 {
00623     int dummy;
00624     register ptr_t hottest = (ptr_t)((word)(&dummy) & ~(HBLKSIZE-1));
00625     register GC_thread me = GC_lookup_thread(thr_self());
00626     register size_t stack_size = me -> stack_size;
00627     register ptr_t stack;
00628     
00629     if (stack_size == 0) {
00630       /* original thread */
00631         struct rlimit rl;
00632          
00633         if (getrlimit(RLIMIT_STACK, &rl) != 0) ABORT("getrlimit failed");
00634         /* Empirically, what should be the stack page with lowest     */
00635         /* address is actually inaccessible.                          */
00636         stack_size = ((word)rl.rlim_cur & ~(HBLKSIZE-1)) - GC_page_sz;
00637         stack = GC_stackbottom - stack_size + GC_page_sz;
00638     } else {
00639         stack = me -> stack;
00640     }
00641     if (stack > hottest || stack + stack_size < hottest) {
00642        ABORT("sp out of bounds");
00643     }
00644     GC_is_fresh((struct hblk *)stack, divHBLKSZ(hottest - stack));
00645 }
00646 
00647 
00648 /* We hold allocation lock.  We assume the world is stopped.   */
00649 void GC_push_all_stacks()
00650 {
00651     register int i;
00652     register GC_thread p;
00653     register ptr_t sp = GC_approx_sp();
00654     register ptr_t bottom, top;
00655     struct rlimit rl;
00656     
00657 #   define PUSH(bottom,top) \
00658       if (GC_dirty_maintained) { \
00659        GC_push_dirty((bottom), (top), GC_page_was_ever_dirty, \
00660                     GC_push_all_stack); \
00661       } else { \
00662         GC_push_all_stack((bottom), (top)); \
00663       }
00664     GC_push_all_stack((ptr_t)GC_lwp_registers,
00665                     (ptr_t)GC_lwp_registers
00666                     + max_lwps * sizeof(GC_lwp_registers[0]));
00667     for (i = 0; i < THREAD_TABLE_SZ; i++) {
00668       for (p = GC_threads[i]; p != 0; p = p -> next) {
00669         if (p -> stack_size != 0) {
00670             bottom = p -> stack;
00671             top = p -> stack + p -> stack_size;
00672         } else {
00673             /* The original stack. */
00674             if (getrlimit(RLIMIT_STACK, &rl) != 0) ABORT("getrlimit failed");
00675             bottom = GC_stackbottom - rl.rlim_cur + GC_page_sz;
00676             top = GC_stackbottom;
00677         }
00678         if ((word)sp > (word)bottom && (word)sp < (word)top) bottom = sp;
00679         PUSH(bottom, top);
00680       }
00681     }
00682 }
00683 
00684 
00685 int GC_is_thread_stack(ptr_t addr)
00686 {
00687     register int i;
00688     register GC_thread p;
00689     register ptr_t bottom, top;
00690     struct rlimit rl;
00691     
00692     for (i = 0; i < THREAD_TABLE_SZ; i++) {
00693       for (p = GC_threads[i]; p != 0; p = p -> next) {
00694         if (p -> stack_size != 0) {
00695             if (p -> stack <= addr &&
00696               addr < p -> stack + p -> stack_size)
00697                   return 1;
00698        }
00699       }
00700     }
00701 }
00702 
00703 /* The only thread that ever really performs a thr_join.       */
00704 void * GC_thr_daemon(void * dummy)
00705 {
00706     void *status;
00707     thread_t departed;
00708     register GC_thread t;
00709     register int i;
00710     register int result;
00711     
00712     for(;;) {
00713       start:
00714         result = thr_join((thread_t)0, &departed, &status);
00715        LOCK();
00716        if (result != 0) {
00717            /* No more threads; wait for create. */
00718            for (i = 0; i < THREAD_TABLE_SZ; i++) {
00719                for (t = GC_threads[i]; t != 0; t = t -> next) {
00720                     if (!(t -> flags & (DETACHED | FINISHED))) {
00721                       UNLOCK();
00722                       goto start; /* Thread started just before we */
00723                                      /* acquired the lock.               */
00724                     }
00725                 }
00726             }
00727             cond_wait(&GC_create_cv, &GC_allocate_ml);
00728             UNLOCK();
00729        } else {
00730            t = GC_lookup_thread(departed);
00731            GC_multithreaded--;
00732            if (!(t -> flags & CLIENT_OWNS_STACK)) {
00733               GC_stack_free(t -> stack, t -> stack_size);
00734            }
00735            if (t -> flags & DETACHED) {
00736               GC_delete_thread(departed);
00737            } else {
00738                t -> status = status;
00739               t -> flags |= FINISHED;
00740               cond_signal(&(t -> join_cv));
00741               cond_broadcast(&GC_prom_join_cv);
00742            }
00743            UNLOCK();
00744        }
00745     }
00746 }
00747 
00748 /* We hold the allocation lock, or caller ensures that 2 instances    */
00749 /* cannot be invoked concurrently.                             */
00750 void GC_thr_init(void)
00751 {
00752     GC_thread t;
00753     thread_t tid;
00754 
00755     if (GC_thr_initialized)
00756            return;
00757     GC_thr_initialized = TRUE;
00758     GC_min_stack_sz = ((thr_min_stack() + 32*1024 + HBLKSIZE-1)
00759                      & ~(HBLKSIZE - 1));
00760     GC_page_sz = sysconf(_SC_PAGESIZE);
00761 #ifdef MMAP_STACKS
00762     GC_zfd = open("/dev/zero", O_RDONLY);
00763     if (GC_zfd == -1)
00764            ABORT("Can't open /dev/zero");
00765 #endif /* MMAP_STACKS */
00766     cond_init(&GC_prom_join_cv, USYNC_THREAD, 0);
00767     cond_init(&GC_create_cv, USYNC_THREAD, 0);
00768     /* Add the initial thread, so we can stop it.       */
00769       t = GC_new_thread(thr_self());
00770       t -> stack_size = 0;
00771       t -> flags = DETACHED | CLIENT_OWNS_STACK;
00772     if (thr_create(0 /* stack */, 0 /* stack_size */, GC_thr_daemon,
00773                  0 /* arg */, THR_DETACHED | THR_DAEMON,
00774                  &tid /* thread_id */) != 0) {
00775        ABORT("Cant fork daemon");
00776     }
00777     thr_setprio(tid, 126);
00778 }
00779 
00780 /* We acquire the allocation lock to prevent races with        */
00781 /* stopping/starting world.                             */
00782 /* This is no more correct than the underlying Solaris 2.X     */
00783 /* implementation.  Under 2.3 THIS IS BROKEN.                  */
00784 int GC_thr_suspend(thread_t target_thread)
00785 {
00786     GC_thread t;
00787     int result;
00788     
00789     LOCK();
00790     result = thr_suspend(target_thread);
00791     if (result == 0) {
00792        t = GC_lookup_thread(target_thread);
00793        if (t == 0) ABORT("thread unknown to GC");
00794         t -> flags |= SUSPENDED;
00795     }
00796     UNLOCK();
00797     return(result);
00798 }
00799 
00800 int GC_thr_continue(thread_t target_thread)
00801 {
00802     GC_thread t;
00803     int result;
00804     
00805     LOCK();
00806     result = thr_continue(target_thread);
00807     if (result == 0) {
00808        t = GC_lookup_thread(target_thread);
00809        if (t == 0) ABORT("thread unknown to GC");
00810         t -> flags &= ~SUSPENDED;
00811     }
00812     UNLOCK();
00813     return(result);
00814 }
00815 
00816 int GC_thr_join(thread_t wait_for, thread_t *departed, void **status)
00817 {
00818     register GC_thread t;
00819     int result = 0;
00820     
00821     LOCK();
00822     if (wait_for == 0) {
00823         register int i;
00824         register GC_bool thread_exists;
00825     
00826        for (;;) {
00827          thread_exists = FALSE;
00828          for (i = 0; i < THREAD_TABLE_SZ; i++) {
00829            for (t = GC_threads[i]; t != 0; t = t -> next) {
00830               if (!(t -> flags & DETACHED)) {
00831                 if (t -> flags & FINISHED) {
00832                   goto found;
00833                 }
00834                 thread_exists = TRUE;
00835               }
00836             }
00837           }
00838           if (!thread_exists) {
00839               result = ESRCH;
00840              goto out;
00841           }
00842           cond_wait(&GC_prom_join_cv, &GC_allocate_ml);
00843         }
00844     } else {
00845         t = GC_lookup_thread(wait_for);
00846        if (t == 0 || t -> flags & DETACHED) {
00847            result = ESRCH;
00848            goto out;
00849        }
00850        if (wait_for == thr_self()) {
00851            result = EDEADLK;
00852            goto out;
00853        }
00854        while (!(t -> flags & FINISHED)) {
00855             cond_wait(&(t -> join_cv), &GC_allocate_ml);
00856        }
00857        
00858     }
00859   found:
00860     if (status) *status = t -> status;
00861     if (departed) *departed = t -> id;
00862     cond_destroy(&(t -> join_cv));
00863     GC_delete_thread(t -> id);
00864   out:
00865     UNLOCK();
00866     return(result);
00867 }
00868 
00869 
00870 int
00871 GC_thr_create(void *stack_base, size_t stack_size,
00872               void *(*start_routine)(void *), void *arg, long flags,
00873               thread_t *new_thread)
00874 {
00875     int result;
00876     GC_thread t;
00877     thread_t my_new_thread;
00878     word my_flags = 0;
00879     void * stack = stack_base;
00880    
00881     LOCK();
00882     if (!GC_thr_initialized)
00883     {
00884     GC_thr_init();
00885     }
00886     GC_multithreaded++;
00887     if (stack == 0) {
00888        if (stack_size == 0) stack_size = GC_min_stack_sz;
00889        stack = (void *)GC_stack_alloc(&stack_size);
00890        if (stack == 0) {
00891            GC_multithreaded--;
00892            UNLOCK();
00893            return(ENOMEM);
00894        }
00895     } else {
00896        my_flags |= CLIENT_OWNS_STACK;
00897     }
00898     if (flags & THR_DETACHED) my_flags |= DETACHED;
00899     if (flags & THR_SUSPENDED) my_flags |= SUSPENDED;
00900     result = thr_create(stack, stack_size, start_routine,
00901                       arg, flags & ~THR_DETACHED, &my_new_thread);
00902     if (result == 0) {
00903         t = GC_new_thread(my_new_thread);
00904         t -> flags = my_flags;
00905         if (!(my_flags & DETACHED)) cond_init(&(t -> join_cv), USYNC_THREAD, 0);
00906         t -> stack = stack;
00907         t -> stack_size = stack_size;
00908         if (new_thread != 0) *new_thread = my_new_thread;
00909         cond_signal(&GC_create_cv);
00910     } else {
00911        GC_multithreaded--;
00912         if (!(my_flags & CLIENT_OWNS_STACK)) {
00913            GC_stack_free(stack, stack_size);
00914        }
00915     }        
00916     UNLOCK();  
00917     return(result);
00918 }
00919 
00920 # else /* SOLARIS_THREADS */
00921 
00922 #ifndef LINT
00923   int GC_no_sunOS_threads;
00924 #endif
00925 #endif