#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; static uint32_t first; static uint8_t init=0; 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)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() { next=&(data[0]); data_addr=next; first=next; if(next%4096)kpanic("kmalloc data not aligned properly."); klog("In-Kernel Block Memory Allocation Initialized at: 0x%08X (free: %d x 4096KB BLOCKS)",next,BLOCKS); init=1; } // kernel block memory allocation // uint32_t kballoc(uint32_t size) { if(size>255)kpanic("max supported size 255 blocks"); spinlock_spin(SPINLOCK_ALLOC); if(!init)kmallocinit(); uint32_t blk=free_cont(size); if(blk==BLOCKS)kpanic("out of mem"); mark_used(blk,size); spinlock_release(SPINLOCK_ALLOC); 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 ad 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; for(int i=0;i