#include "kernel.h" #include "kmalloc.h" #include "spinlock.h" #include "log.h" #define BLOCKS (KMALLOC_MEM_SIZE/KMALLOC_BLOCK_SIZE) // this is in .bss so we can assume it was zeroed! static uint8_t data[KMALLOC_MEM_SIZE] __attribute__((aligned (4096))); // bytes static uint8_t map[BLOCKS]; // static uint32_t data_addr; static uint32_t next_free(uint32_t start) { for(int i=start;i=max)return i; } return BLOCKS; // all free } static uint32_t free_cont(uint32_t blocks) { uint32_t pos=0; while(1) { pos=next_free(pos); // klog("next_free:%d",pos); if(pos+blocks>=BLOCKS)return BLOCKS; // out of mem uint32_t end=next_used(pos,blocks); // klog("next_used:%d",end); if(end-pos>=blocks)return pos; // klog("here we have only %d blocks but we need at least %d",end-pos+1,blocks); pos=end; } } static void mark_used(uint32_t start,uint32_t blocks) { uint32_t b=blocks; for(int i=start;i1)mark_free(start+1,blocks-1); } // will be initialized on first call to kballoc() // static void kmallocinit() { data_addr=data; if(data_addr%4096)kpanic("kmalloc data not aligned properly."); klog("In-Kernel Block Memory Allocation Initialized at: 0x%08X (free: %d x 4096KB BLOCKS)",data_addr,BLOCKS); } // kernel block memory allocation // uint32_t kballoc(uint32_t size) { static bool init=false; if(size>255)kpanic("max supported size 255 blocks"); spinlock_spin(SPINLOCK_ALLOC); if(!init){kmallocinit(); init=true;} uint32_t blk=free_cont(size); if(blk==BLOCKS)kpanic("out of mem"); mark_used(blk,size); spinlock_release(SPINLOCK_ALLOC); //klog("allocated %d blocks at 0x%08X",size,data_addr+blk*4096); return data_addr+blk*4096; } void kbfree(uint32_t pos) { uint32_t blk=(pos-data_addr)/4096; spinlock_spin(SPINLOCK_ALLOC); klog("freeing %d blocks at 0x%08X",map[blk],pos); mark_free(blk,map[blk]); spinlock_release(SPINLOCK_ALLOC); } void kmalloc_sysfs(ringbuffer *r,void (*f)(ringbuffer *r,char *fmt, ...)) { uint32_t free=0; uint32_t used=0; char cmap[BLOCKS]; cmap[200]=0; for(int i=0;i