home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / bsd_srcs / bin / csh / alloc.c next >
Encoding:
C/C++ Source or Header  |  1992-02-05  |  13.7 KB  |  543 lines

  1. /*-
  2.  * Copyright (c) 1983, 1991 The Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions
  7.  * are met:
  8.  * 1. Redistributions of source code must retain the above copyright
  9.  *    notice, this list of conditions and the following disclaimer.
  10.  * 2. Redistributions in binary form must reproduce the above copyright
  11.  *    notice, this list of conditions and the following disclaimer in the
  12.  *    documentation and/or other materials provided with the distribution.
  13.  * 3. All advertising materials mentioning features or use of this software
  14.  *    must display the following acknowledgement:
  15.  *    This product includes software developed by the University of
  16.  *    California, Berkeley and its contributors.
  17.  * 4. Neither the name of the University nor the names of its contributors
  18.  *    may be used to endorse or promote products derived from this software
  19.  *    without specific prior written permission.
  20.  *
  21.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  22.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  25.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31.  * SUCH DAMAGE.
  32.  */
  33.  
  34. #ifndef lint
  35. static char sccsid[] = "@(#)alloc.c    5.12 (Berkeley) 2/5/92";
  36. #endif /* not lint */
  37.  
  38. /*
  39.  * tc.alloc.c from malloc.c (Caltech) 2/21/82
  40.  * Chris Kingsley, kingsley@cit-20.
  41.  *
  42.  * This is a very fast storage allocator.  It allocates blocks of a small
  43.  * number of different sizes, and keeps free lists of each size.  Blocks that
  44.  * don't exactly fit are passed up to the next larger size.  In this
  45.  * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
  46.  * This is designed for use in a program that uses vast quantities of memory,
  47.  * but bombs when it runs out.
  48.  */
  49.  
  50. #include <sys/types.h>
  51. #include <unistd.h>
  52. #include <string.h>
  53. #if __STDC__
  54. # include <stdarg.h>
  55. #else
  56. # include <varargs.h>
  57. #endif
  58.  
  59. #include "csh.h"
  60. #include "extern.h"
  61.  
  62. char   *memtop = NULL;        /* PWP: top of current memory */
  63. char   *membot = NULL;        /* PWP: bottom of allocatable memory */
  64.  
  65. #ifndef SYSMALLOC
  66.  
  67. #undef RCHECK
  68. #undef DEBUG
  69.  
  70.  
  71. #ifndef NULL
  72. #define    NULL 0
  73. #endif
  74.  
  75.  
  76. /*
  77.  * The overhead on a block is at least 4 bytes.  When free, this space
  78.  * contains a pointer to the next free block, and the bottom two bits must
  79.  * be zero.  When in use, the first byte is set to MAGIC, and the second
  80.  * byte is the size index.  The remaining bytes are for alignment.
  81.  * If range checking is enabled and the size of the block fits
  82.  * in two bytes, then the top two bytes hold the size of the requested block
  83.  * plus the range checking words, and the header word MINUS ONE.
  84.  */
  85.  
  86. #define ROUNDUP    7
  87.  
  88. #define MEMALIGN(a) (((a) + ROUNDUP) & ~ROUNDUP)
  89.  
  90. union overhead {
  91.     union overhead *ov_next;    /* when free */
  92.     struct {
  93.     u_char  ovu_magic;    /* magic number */
  94.     u_char  ovu_index;    /* bucket # */
  95. #ifdef RCHECK
  96.     u_short ovu_size;    /* actual block size */
  97.     u_int   ovu_rmagic;    /* range magic number */
  98. #endif
  99.     }       ovu;
  100. #define    ov_magic    ovu.ovu_magic
  101. #define    ov_index    ovu.ovu_index
  102. #define    ov_size        ovu.ovu_size
  103. #define    ov_rmagic    ovu.ovu_rmagic
  104. };
  105.  
  106. #define    MAGIC        0xfd    /* magic # on accounting info */
  107. #define RMAGIC        0x55555555    /* magic # on range info */
  108. #ifdef RCHECK
  109. #define    RSLOP        sizeof (u_int)
  110. #else
  111. #define    RSLOP        0
  112. #endif
  113.  
  114. /*
  115.  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
  116.  * smallest allocatable block is 8 bytes.  The overhead information
  117.  * precedes the data area returned to the user.
  118.  */
  119. #define    NBUCKETS 30
  120. static union overhead *nextf[NBUCKETS];
  121.  
  122. static int    findbucket __P((union overhead *, int));
  123. static void    morecore __P((int));
  124.  
  125. /*
  126.  * nmalloc[i] is the difference between the number of mallocs and frees
  127.  * for a given block size.
  128.  */
  129. static u_int nmalloc[NBUCKETS];
  130.  
  131.  
  132. #ifdef DEBUG
  133. #define CHECK(a, str, p) \
  134.     if (a) { \
  135.     (void) fprintfcsherr, (str, p);    \
  136.     (void) fprintf(csherr, "memtop = %lx membot = %lx.\n", memtop, membot);\
  137.     abort(); \
  138.     }    \
  139.     else
  140. #else
  141. #define CHECK(a, str, p) \
  142.     if (a) { \
  143.     (void) fprintf(csherr, str, p);    \
  144.     (void) fprintf(csherr, "memtop = %lx membot = %lx.\n", memtop, membot);\
  145.     return; \
  146.     }    \
  147.     else
  148. #endif
  149.  
  150. ptr_t
  151. malloc(nbytes)
  152.     register size_t nbytes;
  153. {
  154. #ifndef lint
  155.     register union overhead *p;
  156.     register int bucket = 0;
  157.     register unsigned shiftr;
  158.  
  159.     /*
  160.      * Convert amount of memory requested into closest block size stored in
  161.      * hash buckets which satisfies request.  Account for space used per block
  162.      * for accounting.
  163.      */
  164.     nbytes = MEMALIGN(MEMALIGN(sizeof(union overhead)) + nbytes + RSLOP);
  165.     shiftr = (nbytes - 1) >> 2;
  166.  
  167.     /* apart from this loop, this is O(1) */
  168.     while (shiftr >>= 1)
  169.     bucket++;
  170.     /*
  171.      * If nothing in hash bucket right now, request more memory from the
  172.      * system.
  173.      */
  174.     if (nextf[bucket] == NULL)
  175.     morecore(bucket);
  176.     if ((p = (union overhead *) nextf[bucket]) == NULL) {
  177.     child++;
  178. #ifndef DEBUG
  179.     stderror(ERR_NOMEM);
  180. #else
  181.     showall();
  182.     (void) fprintf(csherr, "nbytes=%d: Out of memory\n", nbytes);
  183.     abort();
  184. #endif
  185.     /* fool lint */
  186.     return ((ptr_t) 0);
  187.     }
  188.     /* remove from linked list */
  189.     nextf[bucket] = nextf[bucket]->ov_next;
  190.     p->ov_magic = MAGIC;
  191.     p->ov_index = bucket;
  192.     nmalloc[bucket]++;
  193. #ifdef RCHECK
  194.     /*
  195.      * Record allocated size of block and bound space with magic numbers.
  196.      */
  197.     if (nbytes <= 0x10000)
  198.     p->ov_size = nbytes - 1;
  199.     p->ov_rmagic = RMAGIC;
  200.     *((u_int *) (((caddr_t) p) + nbytes - RSLOP)) = RMAGIC;
  201. #endif
  202.     return ((ptr_t) (((caddr_t) p) + MEMALIGN(sizeof(union overhead))));
  203. #else
  204.     if (nbytes)
  205.     return ((ptr_t) 0);
  206.     else
  207.     return ((ptr_t) 0);
  208. #endif                /* !lint */
  209. }
  210.  
  211. #ifndef lint
  212. /*
  213.  * Allocate more memory to the indicated bucket.
  214.  */
  215. static void
  216. morecore(bucket)
  217.     register int bucket;
  218. {
  219.     register union overhead *op;
  220.     register int rnu;        /* 2^rnu bytes will be requested */
  221.     register int nblks;        /* become nblks blocks of the desired size */
  222.     register int siz;
  223.  
  224.     if (nextf[bucket])
  225.     return;
  226.     /*
  227.      * Insure memory is allocated on a page boundary.  Should make getpageize
  228.      * call?
  229.      */
  230.     op = (union overhead *) sbrk(0);
  231.     memtop = (char *) op;
  232.     if (membot == NULL)
  233.     membot = memtop;
  234.     if ((int) op & 0x3ff) {
  235.     memtop = (char *) sbrk(1024 - ((int) op & 0x3ff));
  236.     memtop += 1024 - ((int) op & 0x3ff);
  237.     }
  238.  
  239.     /* take 2k unless the block is bigger than that */
  240.     rnu = (bucket <= 8) ? 11 : bucket + 3;
  241.     nblks = 1 << (rnu - (bucket + 3));    /* how many blocks to get */
  242.     memtop = (char *) sbrk(1 << rnu);    /* PWP */
  243.     op = (union overhead *) memtop;
  244.     memtop += 1 << rnu;
  245.     /* no more room! */
  246.     if ((int) op == -1)
  247.     return;
  248.     /*
  249.      * Round up to minimum allocation size boundary and deduct from block count
  250.      * to reflect.
  251.      */
  252.     if (((u_int) op) & ROUNDUP) {
  253.     op = (union overhead *) (((u_int) op + (ROUNDUP + 1)) & ~ROUNDUP);
  254.     nblks--;
  255.     }
  256.     /*
  257.      * Add new memory allocated to that on free list for this hash bucket.
  258.      */
  259.     nextf[bucket] = op;
  260.     siz = 1 << (bucket + 3);
  261.     while (--nblks > 0) {
  262.     op->ov_next = (union overhead *) (((caddr_t) op) + siz);
  263.     op = (union overhead *) (((caddr_t) op) + siz);
  264.     }
  265.     op->ov_next = NULL;
  266. }
  267.  
  268. #endif
  269.  
  270. void
  271. free(cp)
  272.     ptr_t   cp;
  273. {
  274. #ifndef lint
  275.     register int size;
  276.     register union overhead *op;
  277.  
  278.     if (cp == NULL)
  279.     return;
  280.     CHECK(!memtop || !membot, "free(%lx) called before any allocations.", cp);
  281.     CHECK(cp > (ptr_t) memtop, "free(%lx) above top of memory.", cp);
  282.     CHECK(cp < (ptr_t) membot, "free(%lx) above top of memory.", cp);
  283.     op = (union overhead *) (((caddr_t) cp) - MEMALIGN(sizeof(union overhead)));
  284.     CHECK(op->ov_magic != MAGIC, "free(%lx) bad block.", cp);
  285.  
  286. #ifdef RCHECK
  287.     if (op->ov_index <= 13)
  288.     CHECK(*(u_int *) ((caddr_t) op + op->ov_size + 1 - RSLOP) != RMAGIC,
  289.           "free(%lx) bad range check.", cp);
  290. #endif
  291.     CHECK(op->ov_index >= NBUCKETS, "free(%lx) bad block index.", cp);
  292.     size = op->ov_index;
  293.     op->ov_next = nextf[size];
  294.     nextf[size] = op;
  295.  
  296.     nmalloc[size]--;
  297.  
  298. #else
  299.     if (cp == NULL)
  300.     return;
  301. #endif
  302. }
  303.  
  304. ptr_t
  305. calloc(i, j)
  306.     size_t  i, j;
  307. {
  308. #ifndef lint
  309.     register char *cp, *scp;
  310.  
  311.     i *= j;
  312.     scp = cp = (char *) xmalloc((size_t) i);
  313.     if (i != 0)
  314.     do
  315.         *cp++ = 0;
  316.     while (--i);
  317.  
  318.     return (scp);
  319. #else
  320.     if (i && j)
  321.     return ((ptr_t) 0);
  322.     else
  323.     return ((ptr_t) 0);
  324. #endif
  325. }
  326.  
  327. /*
  328.  * When a program attempts "storage compaction" as mentioned in the
  329.  * old malloc man page, it realloc's an already freed block.  Usually
  330.  * this is the last block it freed; occasionally it might be farther
  331.  * back.  We have to search all the free lists for the block in order
  332.  * to determine its bucket: 1st we make one pass thru the lists
  333.  * checking only the first block in each; if that fails we search
  334.  * ``realloc_srchlen'' blocks in each list for a match (the variable
  335.  * is extern so the caller can modify it).  If that fails we just copy
  336.  * however many bytes was given to realloc() and hope it's not huge.
  337.  */
  338. #ifndef lint
  339. int     realloc_srchlen = 4;    /* 4 should be plenty, -1 =>'s whole list */
  340. #endif /* lint */
  341.  
  342. ptr_t
  343. realloc(cp, nbytes)
  344.     ptr_t   cp;
  345.     size_t  nbytes;
  346. {
  347. #ifndef lint
  348.     register u_int onb;
  349.     union overhead *op;
  350.     char   *res;
  351.     register int i;
  352.     int     was_alloced = 0;
  353.  
  354.     if (cp == NULL)
  355.     return (malloc(nbytes));
  356.     op = (union overhead *) (((caddr_t) cp) - MEMALIGN(sizeof(union overhead)));
  357.     if (op->ov_magic == MAGIC) {
  358.     was_alloced++;
  359.     i = op->ov_index;
  360.     }
  361.     else
  362.     /*
  363.      * Already free, doing "compaction".
  364.      * 
  365.      * Search for the old block of memory on the free list.  First, check 
  366.      * the most common case (last element free'd), then (this failing) 
  367.      * the last ``realloc_srchlen'' items free'd. If all lookups fail, 
  368.      * then assume the size of the memory block being realloc'd is the 
  369.      * smallest possible.
  370.      */
  371.     if ((i = findbucket(op, 1)) < 0 &&
  372.         (i = findbucket(op, realloc_srchlen)) < 0)
  373.     i = 0;
  374.  
  375.     onb = MEMALIGN(nbytes + MEMALIGN(sizeof(union overhead)) + RSLOP);
  376.  
  377.     /* avoid the copy if same size block */
  378.     if (was_alloced && (onb < (1 << (i + 3))) && (onb >= (1 << (i + 2))))
  379.     return ((ptr_t) cp);
  380.     if ((res = malloc(nbytes)) == NULL)
  381.     return ((ptr_t) 0);
  382.     if (cp != res) {        /* common optimization */
  383.     onb = (1 << (i + 3)) - MEMALIGN(sizeof(union overhead)) - RSLOP;
  384.     bcopy(cp, res, onb < nbytes ? onb : nbytes);
  385.     }
  386.     if (was_alloced)
  387.     free(cp);
  388.     return (res);
  389. #else
  390.     if (cp && nbytes)
  391.     return ((ptr_t) 0);
  392.     else
  393.     return ((ptr_t) 0);
  394. #endif /* !lint */
  395. }
  396.  
  397.  
  398.  
  399. #ifndef lint
  400. /*
  401.  * Search ``srchlen'' elements of each free list for a block whose
  402.  * header starts at ``freep''.  If srchlen is -1 search the whole list.
  403.  * Return bucket number, or -1 if not found.
  404.  */
  405. static int
  406. findbucket(freep, srchlen)
  407.     union overhead *freep;
  408.     int     srchlen;
  409. {
  410.     register union overhead *p;
  411.     register int i, j;
  412.  
  413.     for (i = 0; i < NBUCKETS; i++) {
  414.     j = 0;
  415.     for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
  416.         if (p == freep)
  417.         return (i);
  418.         j++;
  419.     }
  420.     }
  421.     return (-1);
  422. }
  423.  
  424. #endif
  425.  
  426.  
  427. #else                /* SYSMALLOC */
  428.  
  429. /**
  430.  ** ``Protected versions'' of malloc, realloc, calloc, and free
  431.  **
  432.  ** On many systems:
  433.  **
  434.  ** 1. malloc(0) is bad
  435.  ** 2. free(0) is bad
  436.  ** 3. realloc(0, n) is bad
  437.  ** 4. realloc(n, 0) is bad
  438.  **
  439.  ** Also we call our error routine if we run out of memory.
  440.  **/
  441. char   *
  442. Malloc(n)
  443.     size_t  n;
  444. {
  445.     ptr_t   ptr;
  446.  
  447.     n = n ? n : 1;
  448.  
  449.     if ((ptr = malloc(n)) == (ptr_t) 0) {
  450.     child++;
  451.     stderror(ERR_NOMEM);
  452.     }
  453.     return ((char *) ptr);
  454. }
  455.  
  456. char   *
  457. Realloc(p, n)
  458.     ptr_t   p;
  459.     size_t  n;
  460. {
  461.     ptr_t   ptr;
  462.  
  463.     n = n ? n : 1;
  464.     if ((ptr = (p ? realloc(p, n) : malloc(n))) == (ptr_t) 0) {
  465.     child++;
  466.     stderror(ERR_NOMEM);
  467.     }
  468.     return ((char *) ptr);
  469. }
  470.  
  471. char   *
  472. Calloc(s, n)
  473.     size_t  s, n;
  474. {
  475.     char   *sptr;
  476.     ptr_t   ptr;
  477.  
  478.     n *= s;
  479.     n = n ? n : 1;
  480.     if ((ptr = malloc(n)) == (ptr_t) 0) {
  481.     child++;
  482.     stderror(ERR_NOMEM);
  483.     }
  484.  
  485.     sptr = (char *) ptr;
  486.     if (n != 0)
  487.     do
  488.         *sptr++ = 0;
  489.     while (--n);
  490.  
  491.     return ((char *) ptr);
  492. }
  493.  
  494. void
  495. Free(p)
  496.     ptr_t   p;
  497. {
  498.     if (p)
  499.     free(p);
  500. }
  501.  
  502. #endif                /* SYSMALLOC */
  503.  
  504. /*
  505.  * mstats - print out statistics about malloc
  506.  *
  507.  * Prints two lines of numbers, one showing the length of the free list
  508.  * for each size category, the second showing the number of mallocs -
  509.  * frees for each size category.
  510.  */
  511. void
  512. /*ARGSUSED*/
  513. showall(v, t)
  514.     Char **v;
  515.     struct command *t;
  516. {
  517. #ifndef SYSMALLOC
  518.     register int i, j;
  519.     register union overhead *p;
  520.     int     totfree = 0, totused = 0;
  521.  
  522.     (void) fprintf(cshout, "csh current memory allocation:\nfree:\t");
  523.     for (i = 0; i < NBUCKETS; i++) {
  524.     for (j = 0, p = nextf[i]; p; p = p->ov_next, j++);
  525.     (void) fprintf(cshout, " %4d", j);
  526.     totfree += j * (1 << (i + 3));
  527.     }
  528.     (void) fprintf(cshout, "\nused:\t");
  529.     for (i = 0; i < NBUCKETS; i++) {
  530.     (void) fprintf(cshout, "%4d", nmalloc[i]);
  531.     totused += nmalloc[i] * (1 << (i + 3));
  532.     }
  533.     (void) fprintf(cshout, "\n\tTotal in use: %d, total free: %d\n",
  534.         totused, totfree);
  535.     (void) fprintf(cshout, 
  536.         "\tAllocated memory from 0x%lx to 0x%lx.  Real top at 0x%lx\n",
  537.         membot, memtop, (char *) sbrk(0));
  538. #else
  539.     (void) fprintf(cshout, "Allocated memory from 0x%lx to 0x%lx (%ld).\n",
  540.         membot, memtop = (char *) sbrk(0), memtop - membot);
  541. #endif                /* SYSMALLOC */
  542. }
  543.