void init_memory_block() { /*Initialize the memory chunk */ memory_chunk = malloc(MAX_MEMORY); if (NULL == memory_chunk) { printf ("ERROR: Malloc failed\n"); exit(1); } /*Initialize the free memory list */ insert_free_list(memory_chunk, MAX_MEMORY); /* Initialize the busy list*/ busyblock = NULL; }
static void *coalesce(void *bp) { size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp))) || (PREV_BLKP(bp) == bp); size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp))); size_t size = GET_SIZE(HDRP(bp)); if (prev_alloc && next_alloc) { // Do nothing } else if (prev_alloc && !next_alloc) { size += GET_SIZE(HDRP(NEXT_BLKP(bp))); remove_block(NEXT_BLKP(bp),GET_SIZE(HDRP(NEXT_BLKP(bp)))); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size,0)); } else if (!prev_alloc && next_alloc) { size += GET_SIZE(HDRP(PREV_BLKP(bp))); bp = PREV_BLKP(bp); remove_block(bp,GET_SIZE(HDRP(bp))); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size, 0)); } else { size += GET_SIZE(HDRP(PREV_BLKP(bp))) + GET_SIZE(HDRP(NEXT_BLKP(bp))); void *pbp = PREV_BLKP(bp); remove_block(pbp, GET_SIZE(HDRP(pbp))); void *nbp = NEXT_BLKP(bp); remove_block(nbp, GET_SIZE(HDRP(nbp))); bp = PREV_BLKP(bp); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size, 0)); } insert_free_list(bp,size); return bp; }
void cache_block_put(struct file_buffer *entry) { struct cache *cache; /* * Finished with this cache entry, once the usage count reaches zero it * can be reused. * * If noshrink_lookup is set, put the block onto the free list. * As blocks remain accessible via the hash table they can be found * getting a new lease of life before they are reused. * * if noshrink_lookup is not set then shrink the cache. */ if(entry == NULL) return; cache = entry->cache; pthread_cleanup_push((void *) pthread_mutex_unlock, &cache->mutex); pthread_mutex_lock(&cache->mutex); entry->used --; if(entry->used == 0) { if(cache->noshrink_lookup) { insert_free_list(&cache->free_list, entry); cache->used --; } else { free(entry); cache->count --; } /* One or more threads may be waiting on this block */ pthread_cond_signal(&cache->wait_for_free); } pthread_cleanup_pop(1); }
int my_memfree(void *mem_addr) { unsigned int s = 0; /* size of the block */ busy_list_node *p = busyblock; /*traversing variable of the linked list*/ void *alloc = NULL; busy_list_node *q = NULL; /*previous node of the traversing variable p*/ /* Search for this address's node in the busy link list */ while((NULL != p) && (p->addr != mem_addr)) { q = p; p = p->next; } if (NULL != p) { /* Retrieve the size of this block of memory */ s = p->size; /* Add this block to the free list */ insert_free_list(p->addr, p->size); /* Remove this block from the busy list */ if (NULL == q) { busyblock = p->next; } else { q->next = p->next; } free((void *)p); return 1; } else { return 0; } }