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