alloc.c

Go to the documentation of this file.
00001 /* alloc.c
00002  * Memory Manager */
00003 
00004 
00005 #include <sys/types.h>
00006 #include <lib/alloc.h>
00007 #include <lib/routix.h>
00008 
00009 
00010 
00011 
00012 //typedef union header Header;
00013 
00014 static Header base;
00015 static Header *freep=NULL;
00016 
00017 
00018 void *malloc (unsigned nbytes)
00019 {
00020     Header *p, *prevp;
00021     unsigned nunits;
00022     nunits = (nbytes + sizeof(Header)-1) / sizeof(Header) +1;
00023     if ((prevp = freep)==NULL)
00024     {
00025         base.s.ptr = freep = prevp = &base;
00026         base.s.size = 0;
00027     }
00028 
00029     for ( p=prevp->s.ptr ;   ;  prevp=p , p=p->s.ptr)
00030     {
00031         if (p->s.size >= nunits)
00032         {
00033         
00034             if (p->s.size == nunits)
00035                 prevp->s.ptr = p->s.ptr;
00036             else
00037             {
00038                 p->s.size -= nunits;
00039                 p += p->s.size;
00040                 p->s.size = nunits;
00041             }
00042             freep = prevp;
00043             return (p+1);
00044         }
00045         else if (p==freep) {
00046             if ( (p = morecore()) == NULL ) 
00047                 return NULL;
00048 //          kprintf("\nMorecore entrego: %x\n", p);
00049         }
00050     }
00051         
00052 }
00053 
00054 
00055 
00056 
00057 Header *morecore(void)
00058 {
00059     Header *up;
00060 
00061     up = (Header *) malloc_page();
00062     if (up == NULL)
00063     {
00064 //      printf("Morecore: malloc_page sin memoria\n");
00065         return NULL;
00066     }
00067     printf("Morecore entrego: %x\n", up);
00068 
00069 //    up->s.size= (PAGINA_SIZE + sizeof(Header)-1) / sizeof(Header) +1;
00070     
00071     up->s.size= PAGINA_SIZE / sizeof(Header);
00072     free ( (void *) (up+1));
00073     return freep;
00074 }
00075 
00076 void free (void *ap)
00077 {
00078     Header *bp, *p;
00079 
00080     bp = (Header *) ap - 1;
00081     for (p=freep; ! (bp > p && bp < p->s.ptr) ; p=p->s.ptr)
00082         if ( (p >= p->s.ptr)  &&  (bp > p || bp < p->s.ptr))
00083             break;
00084     if ( (bp + bp->s.size) == p->s.ptr)
00085     {
00086         bp->s.size += p->s.ptr->s.size;
00087         bp->s.ptr = p->s.ptr->s.ptr;
00088     }
00089     else bp->s.ptr = p->s.ptr;
00090 
00091     if ( (p+p->s.size) == bp)
00092     {
00093         p->s.size += bp->s.size;
00094         p->s.ptr = bp->s.ptr;
00095     }
00096     else p->s.ptr = bp;
00097 
00098     freep = p;    
00099 
00100 }
00101 
00102 
00103 
00104 

Generated on Sun May 30 18:38:34 2004 for Routix OS by doxygen 1.3.6