home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / OSK / GRAPHICS / rayshade.lzh / malloc.c < prev    next >
Text File  |  1990-05-08  |  9KB  |  351 lines

  1. #ifndef lint
  2. static char sccsid[] = "@(#)malloc.c    4.3 (Berkeley) 9/16/83";
  3. #endif
  4.  
  5. /*
  6.  * malloc.c (Caltech) 2/21/82
  7.  * Chris Kingsley, kingsley@cit-20.
  8.  *
  9.  * This is a very fast storage allocator.  It allocates blocks of a small
  10.  * number of different sizes, and keeps free lists of each size.  Blocks that
  11.  * don't exactly fit are passed up to the next larger size.  In this
  12.  * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
  13.  * This is designed for use in a program that uses vast quantities of memory,
  14.  * but bombs when it runs out.
  15.  */
  16.  
  17. #include <sys/types.h>
  18.  
  19. #define    NULL 0
  20.  
  21. /*
  22.  * The overhead on a block is at least 4 bytes.  When free, this space
  23.  * contains a pointer to the next free block, and the bottom two bits must
  24.  * be zero.  When in use, the first byte is set to MAGIC, and the second
  25.  * byte is the size index.  The remaining bytes are for alignment.
  26.  * If range checking is enabled and the size of the block fits
  27.  * in two bytes, then the top two bytes hold the size of the requested block
  28.  * plus the range checking words, and the header word MINUS ONE.
  29.  */
  30. union    overhead {
  31.     union    overhead *ov_next;    /* when free */
  32.     struct {
  33.         u_char    ovu_magic;    /* magic number */
  34.         u_char    ovu_index;    /* bucket # */
  35. #ifdef RCHECK
  36.         u_short    ovu_size;    /* actual block size */
  37.         u_int    ovu_rmagic;    /* range magic number */
  38. #endif
  39.     } ovu;
  40. #define    ov_magic    ovu.ovu_magic
  41. #define    ov_index    ovu.ovu_index
  42. #define    ov_size        ovu.ovu_size
  43. #define    ov_rmagic    ovu.ovu_rmagic
  44. };
  45.  
  46. #define    MAGIC        0xff        /* magic # on accounting info */
  47. #define RMAGIC        0x55555555    /* magic # on range info */
  48. #ifdef RCHECK
  49. #define    RSLOP        sizeof (u_int)
  50. #else
  51. #define    RSLOP        0
  52. #endif
  53.  
  54. /*
  55.  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
  56.  * smallest allocatable block is 8 bytes.  The overhead information
  57.  * precedes the data area returned to the user.
  58.  */
  59. #define    NBUCKETS 30
  60. static    union overhead *nextf[NBUCKETS];
  61. extern    char *sbrk();
  62.  
  63. #ifdef MSTATS
  64. /*
  65.  * nmalloc[i] is the difference between the number of mallocs and frees
  66.  * for a given block size.
  67.  */
  68. static    u_int nmalloc[NBUCKETS];
  69. #include <stdio.h>
  70. #endif
  71.  
  72. #ifdef debug
  73. #define    ASSERT(p)   if (!(p)) botch("p"); else
  74. static
  75. botch(s)
  76.     char *s;
  77. {
  78.  
  79.     printf("assertion botched: %s\n", s);
  80.     abort();
  81. }
  82. #else
  83. #define    ASSERT(p)
  84. #endif
  85.  
  86. char *
  87. malloc(nbytes)
  88.     register unsigned nbytes;
  89. {
  90.       register union overhead *p;
  91.       register int bucket = 0;
  92.       register unsigned shiftr;
  93.  
  94.     /*
  95.      * Convert amount of memory requested into
  96.      * closest block size stored in hash buckets
  97.      * which satisfies request.  Account for
  98.      * space used per block for accounting.
  99.      */
  100.       nbytes += sizeof (union overhead) + RSLOP;
  101.       nbytes = (nbytes + 3) &~ 3;
  102.       shiftr = (nbytes - 1) >> 2;
  103.     /* apart from this loop, this is O(1) */
  104.       while (shiftr >>= 1)
  105.           bucket++;
  106.     /*
  107.      * If nothing in hash bucket right now,
  108.      * request more memory from the system.
  109.      */
  110.       if (nextf[bucket] == NULL)
  111.           morecore(bucket);
  112.       if ((p = (union overhead *)nextf[bucket]) == NULL)
  113.           return (NULL);
  114.     /* remove from linked list */
  115.       nextf[bucket] = nextf[bucket]->ov_next;
  116.     p->ov_magic = MAGIC;
  117.     p->ov_index= bucket;
  118. #ifdef MSTATS
  119.       nmalloc[bucket]++;
  120. #endif
  121. #ifdef RCHECK
  122.     /*
  123.      * Record allocated size of block and
  124.      * bound space with magic numbers.
  125.      */
  126.       if (nbytes <= 0x10000)
  127.         p->ov_size = nbytes - 1;
  128.     p->ov_rmagic = RMAGIC;
  129.       *((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
  130. #endif
  131.       return ((char *)(p + 1));
  132. }
  133.  
  134. /*
  135.  * Allocate more memory to the indicated bucket.
  136.  */
  137. static
  138. morecore(bucket)
  139.     register bucket;
  140. {
  141.       register union overhead *op;
  142.       register int rnu;       /* 2^rnu bytes will be requested */
  143.       register int nblks;     /* become nblks blocks of the desired size */
  144.     register int siz;
  145.  
  146.       if (nextf[bucket])
  147.           return;
  148.     /*
  149.      * Insure memory is allocated
  150.      * on a page boundary.  Should
  151.      * make getpageize call?
  152.      */
  153.       op = (union overhead *)sbrk(0);
  154.       if ((int)op & 0x3ff)
  155.           sbrk(1024 - ((int)op & 0x3ff));
  156.     /* take 2k unless the block is bigger than that */
  157.       rnu = (bucket <= 8) ? 11 : bucket + 3;
  158.       nblks = 1 << (rnu - (bucket + 3));  /* how many blocks to get */
  159.       if (rnu < bucket)
  160.         rnu = bucket;
  161.     op = (union overhead *)sbrk(1 << rnu);
  162.     /* no more room! */
  163.       if ((int)op == -1) {
  164.         for (rnu=bucket; rnu < NBUCKETS; rnu++) {
  165.             if (nextf[rnu]) break;
  166.         }
  167.         if (rnu >= NBUCKETS)
  168.             return;
  169.         /* Split into halves until bucket-sized */
  170.         op = nextf[rnu];
  171.         nextf[rnu] = op->ov_next;
  172.         while (--rnu > bucket) {
  173.             siz = 1 << (rnu + 3);
  174.             op->ov_next = nextf[rnu]; /* == NULL */
  175.             nextf[rnu] = op;
  176.             op = (union overhead *)((caddr_t) op + siz);
  177.         }
  178.         nblks = 2;
  179.     }
  180.     /*
  181.      * Round up to minimum allocation size boundary
  182.      * and deduct from block count to reflect.
  183.      */
  184.       if ((int)op & 7) {
  185.           op = (union overhead *)(((int)op + 8) &~ 7);
  186.           nblks--;
  187.       }
  188.     /*
  189.      * Add new memory allocated to that on
  190.      * free list for this hash bucket.
  191.      */
  192.       nextf[bucket] = op;
  193.       siz = 1 << (bucket + 3);
  194.       while (--nblks > 0) {
  195.         op->ov_next = (union overhead *)((caddr_t)op + siz);
  196.         op = (union overhead *)((caddr_t)op + siz);
  197.       }
  198.     op->ov_next = NULL;
  199. }
  200.  
  201. free(cp)
  202.     char *cp;
  203. {
  204.       register int size;
  205.     register union overhead *op;
  206.  
  207.       if (cp == NULL)
  208.           return;
  209.     op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
  210. #ifdef debug
  211.       ASSERT(op->ov_magic == MAGIC);        /* make sure it was in use */
  212. #else
  213.     if (op->ov_magic != MAGIC)
  214.         return;                /* sanity */
  215. #endif
  216. #ifdef RCHECK
  217.       ASSERT(op->ov_rmagic == RMAGIC);
  218.     if (op->ov_index <= 13)
  219.         ASSERT(*(u_int *)((caddr_t)op + op->ov_size + 1 - RSLOP) == RMAGIC);
  220. #endif
  221.       ASSERT(op->ov_index < NBUCKETS);
  222.       size = op->ov_index;
  223.     op->ov_next = nextf[size];
  224.       nextf[size] = op;
  225. #ifdef MSTATS
  226.       nmalloc[size]--;
  227. #endif
  228. }
  229.  
  230. /*
  231.  * When a program attempts "storage compaction" as mentioned in the
  232.  * old malloc man page, it realloc's an already freed block.  Usually
  233.  * this is the last block it freed; occasionally it might be farther
  234.  * back.  We have to search all the free lists for the block in order
  235.  * to determine its bucket: 1st we make one pass thru the lists
  236.  * checking only the first block in each; if that fails we search
  237.  * ``realloc_srchlen'' blocks in each list for a match (the variable
  238.  * is extern so the caller can modify it).  If that fails we just copy
  239.  * however many bytes was given to realloc() and hope it's not huge.
  240.  */
  241. int realloc_srchlen = -1;    /* -1 => search whole list */
  242.  
  243. char *
  244. realloc(cp, nbytes)
  245.     char *cp;
  246.     unsigned nbytes;
  247. {
  248.       register u_int onb;
  249.     union overhead *op;
  250.       char *res;
  251.     register int i;
  252.     int was_alloced = 0;
  253.  
  254.       if (cp == NULL)
  255.           return (malloc(nbytes));
  256.     op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
  257.     if (op->ov_magic == MAGIC) {
  258.         was_alloced++;
  259.         i = op->ov_index;
  260.     } else {
  261.         /*
  262.          * Already free, doing "compaction".
  263.          *
  264.          * Search for the old block of memory on the
  265.          * free list.  First, check the most common
  266.          * case (last element free'd), then (this failing)
  267.          * the last ``realloc_srchlen'' items free'd.
  268.          * If all lookups fail, then assume the size of
  269.          * the memory block being realloc'd is the
  270.          * smallest possible.
  271.          */
  272.         if ((i = findbucket(op, 1)) < 0 &&
  273.             (i = findbucket(op, realloc_srchlen)) < 0)
  274.             i = 0;
  275.     }
  276.     onb = (1 << (i + 3)) - sizeof (*op) - RSLOP;
  277.     /* avoid the copy if same size block */
  278.     if (was_alloced &&
  279.         nbytes <= onb && nbytes > (onb >> 1) - sizeof(*op) - RSLOP) {
  280. #ifdef RCHECK
  281.         op->ov_size = ((nbytes + sizeof(union overhead) + RSLOP) + 3 & ~3) -1;
  282.         *((u_int *)((caddr_t)op + op->ov_size + 1 - RSLOP)) = RMAGIC;
  283. #endif
  284.         return(cp);
  285.     }
  286.       if ((res = malloc(nbytes)) == NULL)
  287.           return (NULL);
  288.       if (cp != res)            /* common optimization */
  289.         bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
  290.       if (was_alloced)
  291.         free(cp);
  292.       return (res);
  293. }
  294.  
  295. /*
  296.  * Search ``srchlen'' elements of each free list for a block whose
  297.  * header starts at ``freep''.  If srchlen is -1 search the whole list.
  298.  * Return bucket number, or -1 if not found.
  299.  */
  300. static
  301. findbucket(freep, srchlen)
  302.     union overhead *freep;
  303.     int srchlen;
  304. {
  305.     register union overhead *p;
  306.     register int i, j;
  307.  
  308.     for (i = 0; i < NBUCKETS; i++) {
  309.         j = 0;
  310.         for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
  311.             if (p == freep)
  312.                 return (i);
  313.             j++;
  314.         }
  315.     }
  316.     return (-1);
  317. }
  318.  
  319. #ifdef MSTATS
  320. /*
  321.  * mstats - print out statistics about malloc
  322.  *
  323.  * Prints two lines of numbers, one showing the length of the free list
  324.  * for each size category, the second showing the number of mallocs -
  325.  * frees for each size category.
  326.  */
  327. mstats(s)
  328.     char *s;
  329. {
  330.       register int i, j;
  331.       register union overhead *p;
  332.       int totfree = 0,
  333.       totused = 0;
  334.  
  335.       fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
  336.       for (i = 0; i < NBUCKETS; i++) {
  337.           for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
  338.               ;
  339.           fprintf(stderr, " %d", j);
  340.           totfree += j * (1 << (i + 3));
  341.       }
  342.       fprintf(stderr, "\nused:\t");
  343.       for (i = 0; i < NBUCKETS; i++) {
  344.           fprintf(stderr, " %d", nmalloc[i]);
  345.           totused += nmalloc[i] * (1 << (i + 3));
  346.       }
  347.       fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
  348.         totused, totfree);
  349. }
  350. #endif
  351.