X-Git-Url: https://eleni.mutantstargoat.com/git/?p=winnie;a=blobdiff_plain;f=src%2Fshalloc.cc;h=b5c155f63ab4b2a58909e1cc9997901f16d41015;hp=d8f97dc508bbeb29d77d6441da65d21e838500ae;hb=e4076629a736e957739c31cd20bbbbb70327023b;hpb=12274901ac01898b01b93e15b5b87dec3348afae diff --git a/src/shalloc.cc b/src/shalloc.cc index d8f97dc..b5c155f 100644 --- a/src/shalloc.cc +++ b/src/shalloc.cc @@ -1,29 +1,171 @@ -#include +#include +#include #include +#include +#include + +#include #include "shalloc.h" #define POOL_SIZE 16777216 -#define BLOCK_SIZE 1024 +#define BLOCK_SIZE 512 + +#define NUM_BLOCKS (POOL_SIZE / BLOCK_SIZE) +#define BITMAP_SIZE (NUM_BLOCKS / 32) + +static bool is_allocated(int block_number); +static int addr_to_block(unsigned char *addr); +static unsigned char *block_to_addr(int block_number); +static void alloc_blocks(int block_pos, int num_blocks); +static void free_blocks(int block_pos, int num_blocks); + +static void print_stats(); static unsigned char *pool; -static std::map alloc_sizes; -//address size +static std::map alloc_sizes; //starting block -> number of blocks + +// 0 means not allocated 1 means allocated +static uint32_t bitmap[BITMAP_SIZE]; + +struct Statistics { + int alloc_num; + int free_num; + int alloc_memsize; + int free_memsize; +}; + +static Statistics stats; bool init_shared_memory() { if(!(pool = (unsigned char *)malloc(POOL_SIZE))) { return false; } + + for(int i=0; i::iterator it; + if((it = alloc_sizes.find(block)) != alloc_sizes.end()) { + int num_blocks = it->second; + free_blocks(block, num_blocks); + alloc_sizes.erase(it); + } + else { + fprintf(stderr, "Attempt to free non-existent blocks from: %d\n", block); + } +} + +static bool is_allocated(int block_number) +{ + int idx = block_number / 32; + int bit_num = block_number % 32; + + if((bitmap[idx] >> bit_num) & 1) { + return true; + } + + return false; +} + +static int addr_to_block(unsigned char *addr) +{ + assert(addr >= pool); + assert(addr < pool + POOL_SIZE); + + return (addr - pool) / BLOCK_SIZE; +} + +static unsigned char *block_to_addr(int block_number) +{ + assert(block_number >= 0); + assert(block_number < NUM_BLOCKS); + + return pool + block_number * BLOCK_SIZE; +} + +static void alloc_blocks(int block_pos, int num_blocks) +{ + for(int i=0; i