home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / prolog / brklyprl.lha / Emulator / myalloc.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-04-14  |  10.6 KB  |  444 lines

  1.  
  2. /* Copyright (C) 1988, 1989 Herve' Touati, Aquarius Project, UC Berkeley */
  3.  
  4. /*
  5.  * Copyright (c) 1983 Regents of the University of California.
  6.  * All rights reserved.  The Berkeley software License Agreement
  7.  * specifies the terms and conditions for redistribution.
  8.  */
  9.  
  10. /*
  11.  * modified by Herve' Touati to serve in a Prolog system.
  12.  */
  13.  
  14. #if defined(LIBC_SCCS) && !defined(lint)
  15. static char sccsid[] = "@(#)malloc.c    5.6 (Berkeley) 3/9/86";
  16. #endif LIBC_SCCS and not lint
  17.  
  18. /*
  19.  * malloc.c (Caltech) 2/21/82
  20.  * Chris Kingsley, kingsley@cit-20.
  21.  *
  22.  * This is a very fast storage allocator.  It allocates blocks of a small 
  23.  * number of different sizes, and keeps free lists of each size.  Blocks that
  24.  * don't exactly fit are passed up to the next larger size.  In this 
  25.  * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
  26.  * This is designed for use in a virtual memory environment.
  27.  */
  28.  
  29. #include <sys/types.h>
  30.  
  31. #define    NULL 0
  32.  
  33. /*
  34.  * The overhead on a block is at least 4 bytes.  When free, this space
  35.  * contains a pointer to the next free block, and the bottom two bits must
  36.  * be zero.  When in use, the first byte is set to MAGIC, and the second
  37.  * byte is the size index.  The remaining bytes are for alignment.
  38.  * If range checking is enabled then a second word holds the size of the
  39.  * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
  40.  * The order of elements is critical: ov_magic must overlay the low order
  41.  * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
  42.  */
  43. union    overhead {
  44.     union    overhead *ov_next;    /* when free */
  45.     struct {
  46.         u_char    ovu_magic;    /* magic number */
  47.         u_char    ovu_index;    /* bucket # */
  48. #ifdef RCHECK
  49.         u_short    ovu_rmagic;    /* range magic number */
  50.         u_int    ovu_size;    /* actual block size */
  51. #endif
  52.     } ovu;
  53. #define    ov_magic    ovu.ovu_magic
  54. #define    ov_index    ovu.ovu_index
  55. #define    ov_rmagic    ovu.ovu_rmagic
  56. #define    ov_size        ovu.ovu_size
  57. };
  58.  
  59. #define    MAGIC        0xef        /* magic # on accounting info */
  60. #define RMAGIC        0x5555        /* magic # on range info */
  61.  
  62. #ifdef RCHECK
  63. #define    RSLOP        sizeof (u_short)
  64. #else
  65. #define    RSLOP        0
  66. #endif
  67.  
  68. /*
  69.  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
  70.  * smallest allocatable block is 8 bytes.  The overhead information
  71.  * precedes the data area returned to the user.
  72.  */
  73. #define    NBUCKETS 30
  74. static    union overhead *nextf[NBUCKETS];
  75. extern    char *sbrk();
  76.  
  77. static    int pagesz;            /* page size */
  78. static    int pagebucket;            /* page size bucket */
  79.  
  80. #ifdef MSTATS
  81. /*
  82.  * nmalloc[i] is the difference between the number of mallocs and frees
  83.  * for a given block size.
  84.  */
  85. static    u_int nmalloc[NBUCKETS];
  86. #include <stdio.h>
  87. #endif
  88.  
  89. #if defined(DEBUG) || defined(RCHECK)
  90. #define    ASSERT(p)   if (!(p)) botch("p")
  91. #include <stdio.h>
  92. static
  93. botch(s)
  94.     char *s;
  95. {
  96.     fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
  97.      (void) fflush(stderr);        /* just in case user buffered it */
  98.     abort();
  99. }
  100. #else
  101. #define    ASSERT(p)
  102. #endif
  103.  
  104. #define MYHEAPSIZE 1048576
  105.  
  106. char *
  107. mysbrk(incr)
  108. int incr;
  109. {
  110.    static char *bottom;
  111.    static char *top;
  112.    static char *current_brk;
  113.    char *first_addr = (char *) (-1);
  114.  
  115.    if (bottom == 0) {
  116.       current_brk = bottom = sbrk(MYHEAPSIZE);
  117. /*    top = bottom + MYHEAPSIZE; */
  118.       top = sbrk(0);
  119.    }
  120.    if (top - current_brk >= incr) {
  121.       first_addr = current_brk;
  122.       current_brk += incr;
  123.    }
  124.    return first_addr;
  125. }
  126.  
  127. char *
  128. malloc(nbytes)
  129.     unsigned nbytes;
  130. {
  131.       register union overhead *op;
  132.       register int bucket;
  133.     register unsigned amt, n;
  134.  
  135.     /*
  136.      * First time malloc is called, setup page size and
  137.      * align break pointer so all data will be page aligned.
  138.      */
  139.     if (pagesz == 0) {
  140.         pagesz = n = getpagesize();
  141.         op = (union overhead *)mysbrk(0);
  142.           n = n - sizeof (*op) - ((int)op & (n - 1));
  143.         if (n < 0)
  144.             n += pagesz;
  145.           if (n) {
  146.               if (mysbrk(n) == (char *)-1)
  147.                 return (NULL);
  148.         }
  149.         bucket = 0;
  150.         amt = 8;
  151.         while (pagesz > amt) {
  152.             amt <<= 1;
  153.             bucket++;
  154.         }
  155.         pagebucket = bucket;
  156.     }
  157.     /*
  158.      * Convert amount of memory requested into closest block size
  159.      * stored in hash buckets which satisfies request.
  160.      * Account for space used per block for accounting.
  161.      */
  162.     if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
  163. #ifndef RCHECK
  164.         amt = 8;    /* size of first bucket */
  165.         bucket = 0;
  166. #else
  167.         amt = 16;    /* size of first bucket */
  168.         bucket = 1;
  169. #endif
  170.         n = -(sizeof (*op) + RSLOP);
  171.     } else {
  172.         amt = pagesz;
  173.         bucket = pagebucket;
  174.     }
  175.     while (nbytes > amt + n) {
  176.         amt <<= 1;
  177.         if (amt == 0)
  178.             return (NULL);
  179.         bucket++;
  180.     }
  181.     /*
  182.      * If nothing in hash bucket right now,
  183.      * request more memory from the system.
  184.      */
  185.       if ((op = nextf[bucket]) == NULL) {
  186.           morecore(bucket);
  187.           if ((op = nextf[bucket]) == NULL)
  188.               return (NULL);
  189.     }
  190.     /* remove from linked list */
  191.       nextf[bucket] = op->ov_next;
  192.     op->ov_magic = MAGIC;
  193.     op->ov_index = bucket;
  194. #ifdef MSTATS
  195.       nmalloc[bucket]++;
  196. #endif
  197. #ifdef RCHECK
  198.     /*
  199.      * Record allocated size of block and
  200.      * bound space with magic numbers.
  201.      */
  202.     op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  203.     op->ov_rmagic = RMAGIC;
  204.       *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
  205. #endif
  206.       return ((char *)(op + 1));
  207. }
  208.  
  209. /*
  210.  * Allocate more memory to the indicated bucket.
  211.  */
  212. morecore(bucket)
  213.     int bucket;
  214. {
  215.       register union overhead *op;
  216.     register int sz;        /* size of desired block */
  217.       int amt;            /* amount to allocate */
  218.       int nblks;            /* how many blocks we get */
  219.  
  220.     /*
  221.      * sbrk_size <= 0 only for big, FLUFFY, requests (about
  222.      * 2^30 bytes on a VAX, I think) or for a negative arg.
  223.      */
  224.     sz = 1 << (bucket + 3);
  225. #ifdef DEBUG
  226.     ASSERT(sz > 0);
  227. #else
  228.     if (sz <= 0)
  229.         return;
  230. #endif
  231.     if (sz < pagesz) {
  232.         amt = pagesz;
  233.           nblks = amt / sz;
  234.     } else {
  235.         amt = sz + pagesz;
  236.         nblks = 1;
  237.     }
  238.     op = (union overhead *)mysbrk(amt);
  239.     /* no more room! */
  240.       if ((int)op == -1)
  241.           return;
  242.     /*
  243.      * Add new memory allocated to that on
  244.      * free list for this hash bucket.
  245.      */
  246.       nextf[bucket] = op;
  247.       while (--nblks > 0) {
  248.         op->ov_next = (union overhead *)((caddr_t)op + sz);
  249.         op = (union overhead *)((caddr_t)op + sz);
  250.       }
  251. }
  252.  
  253. free(cp)
  254.     char *cp;
  255. {   
  256.       register int size;
  257.     register union overhead *op;
  258.  
  259.       if (cp == NULL)
  260.           return;
  261.     op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
  262. #ifdef DEBUG
  263.       ASSERT(op->ov_magic == MAGIC);        /* make sure it was in use */
  264. #else
  265.     if (op->ov_magic != MAGIC)
  266.         return;                /* sanity */
  267. #endif
  268. #ifdef RCHECK
  269.       ASSERT(op->ov_rmagic == RMAGIC);
  270.     ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
  271. #endif
  272.       size = op->ov_index;
  273.       ASSERT(size < NBUCKETS);
  274.     op->ov_next = nextf[size];    /* also clobbers ov_magic */
  275.       nextf[size] = op;
  276. #ifdef MSTATS
  277.       nmalloc[size]--;
  278. #endif
  279. }
  280.  
  281. /*
  282.  * When a program attempts "storage compaction" as mentioned in the
  283.  * old malloc man page, it realloc's an already freed block.  Usually
  284.  * this is the last block it freed; occasionally it might be farther
  285.  * back.  We have to search all the free lists for the block in order
  286.  * to determine its bucket: 1st we make one pass thru the lists
  287.  * checking only the first block in each; if that fails we search
  288.  * ``realloc_srchlen'' blocks in each list for a match (the variable
  289.  * is extern so the caller can modify it).  If that fails we just copy
  290.  * however many bytes was given to realloc() and hope it's not huge.
  291.  */
  292. int realloc_srchlen = 4;    /* 4 should be plenty, -1 =>'s whole list */
  293.  
  294. char *
  295. realloc(cp, nbytes)
  296.     char *cp; 
  297.     unsigned nbytes;
  298. {   
  299.       register u_int onb, i;
  300.     union overhead *op;
  301.       char *res;
  302.     int was_alloced = 0;
  303.  
  304.       if (cp == NULL)
  305.           return (malloc(nbytes));
  306.     op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
  307.     if (op->ov_magic == MAGIC) {
  308.         was_alloced++;
  309.         i = op->ov_index;
  310.     } else {
  311.         /*
  312.          * Already free, doing "compaction".
  313.          *
  314.          * Search for the old block of memory on the
  315.          * free list.  First, check the most common
  316.          * case (last element free'd), then (this failing)
  317.          * the last ``realloc_srchlen'' items free'd.
  318.          * If all lookups fail, then assume the size of
  319.          * the memory block being realloc'd is the
  320.          * largest possible (so that all "nbytes" of new
  321.          * memory are copied into).  Note that this could cause
  322.          * a memory fault if the old area was tiny, and the moon
  323.          * is gibbous.  However, that is very unlikely.
  324.          */
  325.         if ((i = findbucket(op, 1)) < 0 &&
  326.             (i = findbucket(op, realloc_srchlen)) < 0)
  327.             i = NBUCKETS;
  328.     }
  329.     onb = 1 << (i + 3);
  330.     if (onb < pagesz)
  331.         onb -= sizeof (*op) + RSLOP;
  332.     else
  333.         onb += pagesz - sizeof (*op) - RSLOP;
  334.     /* avoid the copy if same size block */
  335.     if (was_alloced) {
  336.         if (i) {
  337.             i = 1 << (i + 2);
  338.             if (i < pagesz)
  339.                 i -= sizeof (*op) + RSLOP;
  340.             else
  341.                 i += pagesz - sizeof (*op) - RSLOP;
  342.         }
  343.         if (nbytes <= onb && nbytes > i) {
  344. #ifdef RCHECK
  345.             op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  346.             *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
  347. #endif
  348.             return(cp);
  349.         } else
  350.             free(cp);
  351.     }
  352.       if ((res = malloc(nbytes)) == NULL)
  353.           return (NULL);
  354.       if (cp != res)        /* common optimization if "compacting" */
  355.         bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
  356.       return (res);
  357. }
  358.  
  359. /*
  360.  * Search ``srchlen'' elements of each free list for a block whose
  361.  * header starts at ``freep''.  If srchlen is -1 search the whole list.
  362.  * Return bucket number, or -1 if not found.
  363.  */
  364. static
  365. findbucket(freep, srchlen)
  366.     union overhead *freep;
  367.     int srchlen;
  368. {
  369.     register union overhead *p;
  370.     register int i, j;
  371.  
  372.     for (i = 0; i < NBUCKETS; i++) {
  373.         j = 0;
  374.         for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
  375.             if (p == freep)
  376.                 return (i);
  377.             j++;
  378.         }
  379.     }
  380.     return (-1);
  381. }
  382.  
  383. #ifdef MSTATS
  384. /*
  385.  * mstats - print out statistics about malloc
  386.  * 
  387.  * Prints two lines of numbers, one showing the length of the free list
  388.  * for each size category, the second showing the number of mallocs -
  389.  * frees for each size category.
  390.  */
  391. mstats(s)
  392.     char *s;
  393. {
  394.       register int i, j;
  395.       register union overhead *p;
  396.       int totfree = 0,
  397.       totused = 0;
  398.  
  399.       fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
  400.       for (i = 0; i < NBUCKETS; i++) {
  401.           for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
  402.               ;
  403.           fprintf(stderr, " %d", j);
  404.           totfree += j * (1 << (i + 3));
  405.       }
  406.       fprintf(stderr, "\nused:\t");
  407.       for (i = 0; i < NBUCKETS; i++) {
  408.           fprintf(stderr, " %d", nmalloc[i]);
  409.           totused += nmalloc[i] * (1 << (i + 3));
  410.       }
  411.       fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
  412.         totused, totfree);
  413. }
  414. #endif
  415.  
  416. int *maxalloc(size)
  417.      int *size;
  418. {
  419.   extern char *brk();
  420.   extern char *sbrk();
  421.   int pagesize = 1024;
  422.   char *bottom;
  423.   int lower = 0;
  424.   int upper = *size;
  425.   int c;
  426.   mysbrk(0);
  427.   bottom = sbrk(0);
  428.   for(;;) {
  429.     if ((upper - lower) < pagesize)
  430.       break;
  431.     c = (lower + upper) / 2;
  432.     if (brk(bottom + c) == (char *) -1)
  433.       upper = c;
  434.     else 
  435.       lower = c;
  436.   }
  437.   sbrk(- pagesize * 10);
  438.   *size = (((int *) sbrk(0)) - ((int *) bottom));
  439.   return (int *) bottom;
  440. }
  441.    
  442.    
  443.    
  444.