home *** CD-ROM | disk | FTP | other *** search
/ Media Share 9 / MEDIASHARE_09.ISO / network / src_1218.zip / ALLOC.C < prev    next >
C/C++ Source or Header  |  1991-12-16  |  10KB  |  406 lines

  1. /* memory allocation routines
  2.  * Copyright 1991 Phil Karn, KA9Q
  3.  *
  4.  * Adapted from alloc routine in K&R; memory statistics and interrupt
  5.  * protection added for use with net package. Must be used in place of
  6.  * standard Turbo-C library routines because the latter check for stack/heap
  7.  * collisions. This causes erroneous failures because process stacks are
  8.  * allocated off the heap.
  9.  */
  10.  
  11. #include <stdio.h>
  12. #include <dos.h>
  13. #include <alloc.h>
  14. #include "global.h"
  15. #include "mbuf.h"
  16. #include "proc.h"
  17. #include "cmdparse.h"
  18.  
  19. static unsigned long Memfail;    /* Count of allocation failures */
  20. static unsigned long Allocs;    /* Total allocations */
  21. static unsigned long Frees;    /* Total frees */
  22. static unsigned long Invalid;    /* Total calls to free with garbage arg */
  23. static unsigned long Intalloc;    /* Calls to malloc with ints disabled */
  24. static unsigned long Intfree;    /* Calls to free with ints disabled */
  25. static int Memwait;        /* Number of tasks waiting for memory */
  26. static unsigned long Yellows;    /* Yellow alert garbage collections */
  27. static unsigned long Reds;    /* Red alert garbage collections */
  28. unsigned long Availmem;        /* Heap memory, ABLKSIZE units */
  29. static unsigned long Morecores;
  30.  
  31. static unsigned long Sizes[16];
  32.  
  33. static int dostat __ARGS((int argc,char *argv[],void *p));
  34. static int dofreelist __ARGS((int argc,char *argv[],void *p));
  35. static int doibufsize __ARGS((int argc,char *argv[],void *p));
  36. static int donibufs __ARGS((int argc,char *argv[],void *p));
  37. static int dothresh __ARGS((int argc,char *argv[],void *p));
  38. static int dosizes __ARGS((int argc,char *argv[],void *p));
  39.  
  40. struct cmds Memcmds[] = {
  41.     "freelist",    dofreelist,    0, 0, NULLCHAR,
  42.     "ibufsize",    doibufsize,    0, 0, NULLCHAR,
  43.     "nibufs",    donibufs,    0, 0, NULLCHAR,
  44.     "sizes",    dosizes,    0, 0, NULLCHAR,
  45.     "status",    dostat,        0, 0, NULLCHAR,
  46.     "thresh",    dothresh,    0, 0, NULLCHAR,
  47.     NULLCHAR,
  48. };
  49.  
  50. #ifdef    LARGEDATA
  51. #define    HUGE    huge
  52. #else
  53. #define    HUGE
  54. #endif
  55.  
  56. union header {
  57.     struct {
  58.         union header HUGE *ptr;
  59.         unsigned long size;
  60.     } s;
  61.     long l[2];
  62. };
  63.  
  64. typedef union header HEADER;
  65. #define    NULLHDR    (HEADER HUGE *)NULL
  66.  
  67. #define    ABLKSIZE    (sizeof (HEADER))
  68.  
  69. static HEADER HUGE *morecore __ARGS((unsigned nu));
  70.  
  71. static HEADER Base;
  72. static HEADER HUGE *Allocp = NULLHDR;
  73. static unsigned long Heapsize;
  74.  
  75. /* Allocate block of 'nb' bytes */
  76. void *
  77. malloc(nb)
  78. unsigned nb;
  79. {
  80.     register HEADER HUGE *p, HUGE *q;
  81.     register unsigned nu;
  82.     int i;
  83.  
  84.     if(!istate())
  85.         Intalloc++;
  86.     if(nb == 0)
  87.         return NULL;
  88.  
  89.     /* Record the size of this request */
  90.     if((i = log2(nb)) >= 0)
  91.         Sizes[i]++;
  92.     
  93.     /* Round up to full block, then add one for header */
  94.     nu = ((nb + ABLKSIZE - 1) / ABLKSIZE) + 1;
  95.     if((q = Allocp) == NULLHDR){
  96.         Base.s.ptr = Allocp = q = &Base;
  97.         Base.s.size = 1;
  98.     }
  99.     for(p = q->s.ptr; ; q = p, p = p->s.ptr){
  100.         if(p->s.size >= nu){
  101.             /* This chunk is at least as large as we need */
  102.             if(p->s.size <= nu + 1){
  103.                 /* This is either a perfect fit (size == nu)
  104.                  * or the free chunk is just one unit larger.
  105.                  * In either case, alloc the whole thing,
  106.                  * because there's no point in keeping a free
  107.                  * block only large enough to hold the header.
  108.                  */
  109.                 q->s.ptr = p->s.ptr;
  110.             } else {
  111.                 /* Carve out piece from end of entry */
  112.                 p->s.size -= nu;
  113.                 p += p->s.size;
  114.                 p->s.size = nu;
  115.             }
  116. #ifdef    circular
  117.             Allocp = q;
  118. #endif
  119.             p->s.ptr = p;    /* for auditing */
  120.             Allocs++;
  121.             Availmem -= p->s.size;
  122.             p++;
  123.             break;
  124.         }
  125.         if(p == Allocp && ((p = morecore(nu)) == NULLHDR)){
  126.             Memfail++;
  127.             break;
  128.         }
  129.     }
  130. #ifdef    LARGEDATA
  131.     /* On the brain-damaged Intel CPUs in "large data" model,
  132.      * make sure the pointer's offset field isn't null
  133.      * (unless the entire pointer is null).
  134.      * The Turbo C compiler and certain
  135.      * library functions like strrchr() assume this.
  136.      */
  137.     if(FP_OFF(p) == 0 && FP_SEG(p) != 0){
  138.         /* Return denormalized but equivalent pointer */
  139.         return (void *)MK_FP(FP_SEG(p)-1,16);
  140.     }
  141. #endif
  142.     return (void *)p;
  143. }
  144. /* Get more memory from the system and put it on the heap */
  145. static HEADER HUGE *
  146. morecore(nu)
  147. unsigned nu;
  148. {
  149.     register char HUGE *cp;
  150.     register HEADER HUGE *up;
  151.  
  152.     Morecores++;
  153.     if ((int)(cp = (char HUGE *)sbrk(nu * ABLKSIZE)) == -1)
  154.         return NULLHDR;
  155.     up = (HEADER *)cp;
  156.     up->s.size = nu;
  157.     up->s.ptr = up;    /* satisfy audit */
  158.     free((void *)(up + 1));
  159.     Heapsize += nu*ABLKSIZE;
  160.     Frees--;    /* Nullify increment inside free() */
  161.     return Allocp;
  162. }
  163.  
  164. /* Put memory block back on heap */
  165. void
  166. free(blk)
  167. void *blk;
  168. {
  169.     register HEADER HUGE *p, HUGE *q;
  170.     unsigned short HUGE *ptr;
  171.  
  172.     if(!istate())
  173.         Intfree++;
  174.     if(blk == NULL)
  175.         return;        /* Required by ANSI */
  176.     p = (HEADER HUGE *)blk - 1;
  177.     /* Audit check */
  178.     if(p->s.ptr != p){
  179.         ptr = (unsigned short *)&blk;
  180.         printf("free: WARNING! invalid pointer (0x%lx) pc = 0x%x %x proc %s\n",ptol(blk),
  181.          ptr[-1],ptr[-2],Curproc->name);
  182.         Invalid++;
  183.         log(-1,"free: WARNING! invalid pointer (0x%lx) pc = 0x%x %x proc %s\n",ptol(blk),
  184.          ptr[-1],ptr[-2],Curproc->name);
  185.         return;
  186.     }
  187.     Availmem += p->s.size;
  188.     /* Search the free list looking for the right place to insert */
  189.     for(q = Allocp; !(p > q && p < q->s.ptr); q = q->s.ptr){
  190.         /* Highest address on circular list? */
  191.         if(q >= q->s.ptr && (p > q || p < q->s.ptr))
  192.             break;
  193.     }
  194.     if(p + p->s.size == q->s.ptr){
  195.         /* Combine with front of this entry */
  196.         p->s.size += q->s.ptr->s.size;
  197.         p->s.ptr = q->s.ptr->s.ptr;
  198.     } else {
  199.         /* Link to front of this entry */
  200.         p->s.ptr = q->s.ptr;
  201.     }
  202.     if(q + q->s.size == p){
  203.         /* Combine with end of this entry */
  204.         q->s.size += p->s.size;
  205.         q->s.ptr = p->s.ptr;
  206.     } else {
  207.         /* Link to end of this entry */
  208.         q->s.ptr = p;
  209.     }
  210. #ifdef    circular
  211.     Allocp = q;
  212. #endif
  213.     Frees++;
  214.     if(Memwait != 0)
  215.         psignal(&Memwait,0);
  216. }
  217.  
  218. #ifdef    notdef    /* Not presently used */
  219. /* Move existing block to new area */
  220. void *
  221. realloc(area,size)
  222. void *area;
  223. unsigned size;
  224. {
  225.     unsigned osize;
  226.     HEADER HUGE *hp;
  227.     char HUGE *cp;
  228.  
  229.     hp = ((HEADER *)area) - 1;
  230.     osize = (hp->s.size -1) * ABLKSIZE;
  231.  
  232.     free(area);
  233.     if((cp = malloc(size)) != NULL && cp != area)
  234.         memcpy((char *)cp,(char *)area,size>osize? osize : size);
  235.     return cp;
  236. }
  237. #endif
  238. /* Allocate block of cleared memory */
  239. void *
  240. calloc(nelem,size)
  241. unsigned nelem;    /* Number of elements */
  242. unsigned size;    /* Size of each element */
  243. {
  244.     register unsigned i;
  245.     register char *cp;
  246.  
  247.     i = nelem * size;
  248.     if((cp = malloc(i)) != NULL)
  249.         memset(cp,0,i);
  250.     return cp;
  251. }
  252. /* Version of malloc() that waits if necessary for memory to become available */
  253. void *
  254. mallocw(nb)
  255. unsigned nb;
  256. {
  257.     register void *p;
  258.  
  259.     while((p = malloc(nb)) == NULL){
  260.         Memwait++;
  261.         pwait(&Memwait);
  262.         Memwait--;
  263.     }
  264.     return p;
  265. }
  266. /* Version of calloc that waits if necessary for memory to become available */
  267. void *
  268. callocw(nelem,size)
  269. unsigned nelem;    /* Number of elements */
  270. unsigned size;    /* Size of each element */
  271. {
  272.     register unsigned i;
  273.     register char *cp;
  274.  
  275.     i = nelem * size;
  276.     cp = mallocw(i);
  277.     memset(cp,0,i);
  278.     return cp;
  279. }
  280. /* Return available memory on our heap plus available system memory */
  281. unsigned long
  282. availmem()
  283. {
  284.     return Availmem * ABLKSIZE + coreleft();
  285. }
  286.  
  287. /* Print heap stats */
  288. static int
  289. dostat(argc,argv,envp)
  290. int argc;
  291. char *argv[];
  292. void *envp;
  293. {
  294.     tprintf("heap size %lu avail %lu (%lu%%) morecores %lu coreleft %lu\n",
  295.      Heapsize,Availmem * ABLKSIZE,100L*Availmem*ABLKSIZE/Heapsize,
  296.      Morecores,coreleft());
  297.     tprintf("allocs %lu frees %lu (diff %lu) alloc fails %lu invalid frees %lu\n",
  298.         Allocs,Frees,Allocs-Frees,Memfail,Invalid);
  299.     tprintf("interrupts-off calls to malloc %lu free %lu\n",Intalloc,Intfree);
  300.     tprintf("garbage collections yellow %lu red %lu\n",Yellows,Reds);
  301.     iqstat();
  302.     return 0;
  303. }
  304.  
  305. /* Print heap free list */
  306. static int
  307. dofreelist(argc,argv,envp)
  308. int argc;
  309. char *argv[];
  310. void *envp;
  311. {
  312.     HEADER HUGE *p;
  313.     int i = 0;
  314.  
  315.     for(p = Base.s.ptr;p != &Base;p = p->s.ptr){
  316.         tprintf("%5lx %6lu",ptol((void *)p),p->s.size * ABLKSIZE);
  317.         if(++i == 4){
  318.             i = 0;
  319.             if(tprintf("\n") == EOF)
  320.                 return 0;
  321.         } else
  322.             tprintf(" | ");
  323.     }
  324.     if(i != 0)
  325.         tprintf("\n");
  326.     return 0;
  327. }
  328. static int
  329. dosizes(argc,argv,p)
  330. int argc;
  331. char *argv[];
  332. void *p;
  333. {
  334.     int i;
  335.  
  336.     for(i=0;i<16;i += 4){
  337.         tprintf("N>=%5u:%7ld| N>=%5u:%7ld| N>=%5u:%7ld| N>=%5u:%7ld\n",
  338.          1<<i,Sizes[i],    2<<i,Sizes[i+1],
  339.          4<<i,Sizes[i+2],8<<i,Sizes[i+3]);
  340.     }
  341.     return 0;
  342. }
  343. int
  344. domem(argc,argv,p)
  345. int argc;
  346. char *argv[];
  347. void *p;
  348. {
  349.     return subcmd(Memcmds,argc,argv,p);
  350. }
  351.  
  352. static int
  353. donibufs(argc,argv,p)
  354. int argc;
  355. char *argv[];
  356. void *p;
  357. {
  358.     return setint(&Nibufs,"Interrupt pool buffers",argc,argv);
  359. }
  360. static int
  361. doibufsize(argc,argv,p)
  362. int argc;
  363. char *argv[];
  364. void *p;
  365. {
  366.     return setuns(&Ibufsize,"Interrupt buffer size",argc,argv);
  367. }
  368.  
  369. static int
  370. dothresh(argc,argv,p)
  371. int argc;
  372. char *argv[];
  373. void *p;
  374. {
  375.     return setlong(&Memthresh,"Free memory threshold (bytes)",argc,argv);
  376. }
  377.  
  378. /* Background memory compactor, used when memory runs low */
  379. void
  380. gcollect(i,v1,v2)
  381. int i;    /* Args not used */
  382. void *v1;
  383. void *v2;
  384. {
  385.     void (**fp)();
  386.     int red;
  387.  
  388.     for(;;){
  389.         pause(1000L);    /* Run every second */
  390.         /* If memory is low, collect some garbage. If memory is VERY
  391.          * low, invoke the garbage collection routines in "red" mode.
  392.          */
  393.         if(availmem() < Memthresh){
  394.             if(availmem() < Memthresh/2){
  395.                 red = 1;
  396.                 Reds++;
  397.             } else {
  398.                 red = 0;
  399.                 Yellows++;
  400.             }
  401.             for(fp = Gcollect;*fp != NULL;fp++)
  402.                 (**fp)(red);
  403.         }
  404.     }
  405. }
  406.