/**
 * ----------------------------------------------------------------------------------
 *
 * Project	: 
 * File Name	: malloc.c
 * Author	: Carlos Pires (c.alexandre.pires@gmail.com)
 * License	: GPL V2
 *
 * Kernel malloc          
 *
 * ----------------------------------------------------------------------------------
 **/

#define MALLOC_SIZE 160
#define MALLOCS ((2UL*1024*1024*1024)/MALLOC_SIZE)

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#define TRUE	      1
#define FALSE         0
#define PAGE_SIZE     4096

/* this defines what sizes will be "filtered" by kmalloc 
 * ex: we want our kmalloc to create a linked list for
 * 1 byte,2 bytes, 4 bytes & 8 bytes, so HANDLED_SIZES = 4.
 * sizes in this range will be searched using best fit, all
 * the others will be using first fit. */ 
#define HANDLED_SIZES     10

/* this is the number of control bytes we have to use to
 * speed up kmalloc, each bit of these control bytes will
 * be set everytime we have a free block in the linked
 * list for that size*/
#define CONTROL_BYTES       HANDLED_SIZES/8

/* decimal number for 10000000 (binary) */
#define LAST_BIT_SIZE       128

/* how many bits per byte */
#define BITS_PER_BYTE       8

/* start offset */
#define START_OFFSET(n)     (((n-1)/LAST_BIT_SIZE)*BITS_PER_BYTE)

/* access control byte i */
#define CONTROL_BYTE(i)     (kmalloc_heap_header->control[i])

/* check if we have a free block for the size n */
#define FREE_BLOCKS(n)      (kmalloc_heap_header->control[n/LAST_BIT_SIZE] & (n))

/* set bit in control bitmap saying that we have a 
 * free block for size n*/
#define S_FREE_BLOCKS(n)    (kmalloc_heap_header->control[n/LAST_BIT_SIZE] |= (n))

/* clean bit in control bitmap saying that we don't have 
 * any free block for size n */
#define C_FREE_BLOCKS(n)    (kmalloc_heap_header->control[n/LAST_BIT_SIZE] &= ~(n))
 
/* get the last freed block */
#define LAST_FREE           (kmalloc_heap_header->last_free_cache)

/* get the first free block for size n */
#define FIRST_FREE(n)       (kmalloc_heap_header->free_list[size_idx(n)])

/* get the first free block for unmanaged sizes */
#define U_FIRST_FREE        (kmalloc_heap_header->first_free_unmanaged)

/* # of free blocks for unmanaged sizes */
#define U_FREE_BLOCKS       (kmalloc_heap_header->free_unmanaged_blocks)

/* total of free blocks */
#define TOTAL_FREE_BLOCKS    (kmalloc_heap_header->free_blocks)

/* if block pointer is valid */
#define IS_VALID_PTR(blk)   (blk!=NULL)

/* if index pointer is valid */
#define IS_VALID_INDEX(i)   (i<HANDLED_SIZES)

/* get block size */
#define BLOCK_FREE(blk)     blk->free

/* get block size */
#define BLOCK_SIZE(blk)     blk->size

/* next block */
#define BLOCK_NEXT(blk)     blk->next_blk

/* previous block */
#define BLOCK_PREV(blk)     blk->prev_blk

/* we allocate pages every time we call sbrk
 * so we may have unused space */
#define BYTES_LEFT          (kmalloc_heap_header->bytes_left_in_page)

#define HEAP_HEADER       struct mm_heap_header
#define BLOCK_HEADER      struct mm_blk_header
#define KMALLOC_TOP_ADDR  kmalloc_heap_header->last_address

BLOCK_HEADER
{
	int          free;
	int          size;
	BLOCK_HEADER *next_blk;
	BLOCK_HEADER *prev_blk;
};

HEAP_HEADER 
{
    unsigned char control[CONTROL_BYTES];
    BLOCK_HEADER *free_list[HANDLED_SIZES];
    BLOCK_HEADER *first_free_unmanaged;
    BLOCK_HEADER *last_free_cache;
    int          free_unmanaged_blocks;
    int          free_blocks;
    int          bytes_left_in_page;
    void         *last_address;
};

static int        kmalloc_initialized = FALSE;
static HEAP_HEADER *kmalloc_heap_header;

int inline align_size(int size)
{
	int i;
	
	for (i=START_OFFSET(size);((1<<i)<size);i++);

	return 1<<i;
}

int inline size_idx(int size)
{
	int i;
	
	for (i=START_OFFSET(size);((1<<i)<size);i++);

	return i;
}

/* initialize kmalloc, including heap block */
void    kmalloc_init    ( void )
{
    int i;

    /* reserve memory for kernel heap header & set header pointer
     * to start at kernel heap entry */
    kmalloc_heap_header = (HEAP_HEADER *) sbrk(0);

    sbrk(sizeof(HEAP_HEADER));    

    /* kmalloc last valid address is after our header*/
    KMALLOC_TOP_ADDR = (unsigned *)kmalloc_heap_header + sizeof(HEAP_HEADER);

    /* first free for every size block is null, 
     * we don't have it */
    for (i=0;i<HANDLED_SIZES;i++)
         FIRST_FREE(i)  = NULL;
    U_FIRST_FREE        = NULL;
    LAST_FREE           = NULL;

    /* clean every control byte, we don't have any
     * free block yet */
    for (i=0;i<CONTROL_BYTES;i++)
         CONTROL_BYTE(i)= 0;
    U_FREE_BLOCKS       = 0;
    TOTAL_FREE_BLOCKS   = 0;
    
    /* we don't have any memory allocated */
    BYTES_LEFT = 0;

    /* our malloc is now initialized */
    kmalloc_initialized = TRUE;

}

/* free a block a link it in our free blocks
 * linked list */
void    kfree    (void *addr) 
{

    BLOCK_HEADER *blk_to_free;
	
    /* backup to block header */
    blk_to_free = (BLOCK_HEADER *)(addr - sizeof(BLOCK_HEADER));

    /* get this block size */
    int blk_size = BLOCK_SIZE(blk_to_free);

    /* free block */
    BLOCK_FREE(blk_to_free) = TRUE;

    /* what is the list we will use? */
    int free_list_index =  size_idx (blk_size);

    /* is this a size handled? */
    if (IS_VALID_INDEX(free_list_index))
    {
    	/* yes */
    	/* do we have already blocks of that size
    	 * freed */
        if (FREE_BLOCKS(blk_size))
        {
            /* yes, so we have to link this one to the last one */
            BLOCK_NEXT(blk_to_free)          = (BLOCK_HEADER *) FIRST_FREE(blk_size);
 
            /* ok now we have our list like this 
             * (this block) -> (last block) -> ... */
        } 
        else 
        {
            /* this is the first free block for this size 
             * we have to set the correct bit in our control
             * byte so we know that we have a free block for
             * this size */
            S_FREE_BLOCKS(blk_size);
        }

        /* now this one is our first free block for this size*/
        FIRST_FREE(blk_size) = (BLOCK_HEADER *) blk_to_free;
         
    }
    else
    {
    	/* no, so this is a unhandled size, treat as a 
    	 * simple free list*/

        /* we do the same procedure as above, the only difference
         * is our linked list and the link process because we link the
         * blocks in both directions. 

         * when we search this list it's possible to have an 
         * suitable block in the middle, and to unlink it we must
         * know the adjacents blocks so we can link them. */

        if (U_FREE_BLOCKS)
        {
             BLOCK_PREV(U_FIRST_FREE) = (BLOCK_HEADER *) blk_to_free;
             BLOCK_NEXT(blk_to_free)  = (BLOCK_HEADER *) U_FIRST_FREE;

            /* ok now we have our list like this 
             * (this block) <-> (last block) <-> ... */
        }

        U_FIRST_FREE = (BLOCK_HEADER *) blk_to_free;
        
        /* we got our selfs a new free block */
        U_FREE_BLOCKS ++;

    }
    
    /* used for fast return, this is the last freed block */
    LAST_FREE = (BLOCK_HEADER *) blk_to_free;

    /* we've done it */
    TOTAL_FREE_BLOCKS++;
    return;
}

/* allocate a free block, by searching the free linked list
 * if none is found, increase heap */
void    *kmalloc    ( int nbytes )
{

    BLOCK_HEADER *blk;
    void *addr   = NULL;
    int block    = 0;
    
    /* if kmalloc is not initialized, do it */
    if (!kmalloc_initialized)
        kmalloc_init();

    /* is there any free block? */
    if (!TOTAL_FREE_BLOCKS) goto reserve_new_block;

    /* align size */
    nbytes = align_size(nbytes);

    /* check if the last freed block can be used */
    if (BLOCK_SIZE(LAST_FREE) == nbytes)
    {
        /* let's get it */
        blk = LAST_FREE;
        
        /* this will be the block we'll return,
         * so store address */
        addr = blk;
        
        /* let's make this block ours */
        BLOCK_FREE(blk) = FALSE;
        
        /* unlink this block from list */
        FIRST_FREE(nbytes) = BLOCK_NEXT(blk);
        
        /* check if we still have a valid block in our list 
         * if not then clean bit */
        if (!IS_VALID_PTR(FIRST_FREE(nbytes)))
            C_FREE_BLOCKS(nbytes);

        /* clean link for safety purposes */
        BLOCK_PREV(blk) = NULL;
        BLOCK_NEXT(blk) = NULL;
        
        /* we got a block less */
        TOTAL_FREE_BLOCKS--;

        /* it's time to return address of this allocated block */
        goto return_address;
    }

    /* last freed is not suitable, start searching in our linked
     * lists */

    /* what list should we use? */
    int blk_list_index =  size_idx (nbytes);
    
    /* is this a size handled? */
    if (IS_VALID_INDEX(blk_list_index))
    {
    	/* yes */
    	
    	/* do we have any free blocks in this list, if no 
    	 * reserve a new block */
        if (!FREE_BLOCKS(nbytes)) goto reserve_new_block;
        
        /* we have free blocks */
        
        /* let's get the first */
        blk = FIRST_FREE(nbytes);
        
        /* this will be the block we'll return,
         * so store address */
        addr = blk;
        
        /* let's make this block ours */
        BLOCK_FREE(blk) = FALSE;
        
        /* unlink this block from list */
        FIRST_FREE(nbytes) = BLOCK_NEXT(blk);
        
        /* check if we still have a valid block in our list 
         * if not then clean bit*/
        if (!IS_VALID_PTR(FIRST_FREE(nbytes)))
            C_FREE_BLOCKS(nbytes);

        /* clean link for safety purposes */
        BLOCK_PREV(blk) = NULL;
        BLOCK_NEXT(blk) = NULL;
        
        /* we got a block less */
        TOTAL_FREE_BLOCKS--;

        /* it's time to return address of this allocated block */
        goto return_address;
    }
    else
    {
    	/* no, this size is not handled */
        /* if we don't have any free blocks available, request
         * it to system */
        if (!U_FREE_BLOCKS) goto reserve_new_block;
        
        /* we have free blocks let's search for one that
         * suits our needs */
     
        /* let's start at our first free block */
        blk = U_FIRST_FREE;
    
        // how many blocks we have to inspect
        block = U_FREE_BLOCKS;
    
        while(block>0)
        {
            /* search for a block that suits our needs */
            if (BLOCK_SIZE(blk) >= nbytes) 
            {
                /* we've got a block */
                /* let's make it our's */
                BLOCK_FREE(blk) = FALSE;
        	
                /* stores block address */
                addr = blk;
        	
                /* is this the first free?
                 * if yes, our next first free block will be our next block 
                 * in the list 
                 * if not we need to link our previous block to our next
                 * block */
                if (block == U_FREE_BLOCKS)
                    U_FIRST_FREE = BLOCK_NEXT(blk);
                else if (block > 1)
                    BLOCK_NEXT(BLOCK_PREV(blk)) = BLOCK_NEXT(blk);
                else
                    BLOCK_NEXT(BLOCK_PREV(blk)) = NULL; /* no more blocks here */
        	
                /* clean link for safety purposes */
            	BLOCK_PREV(blk) = NULL;
                BLOCK_NEXT(blk) = NULL;
        	
            	/* we've got a less free block */
            	U_FREE_BLOCKS--;
        	
            	/* get out of the loop */
                break;
            }
        
            /* this one is not good, let's go next free block */
            blk = BLOCK_NEXT(blk);
        
            block--;
        }
    
        /* check if we've found a block, if not we need reserve 
         * a new block*/

        if (block>0) 
        {
            /* we got a block less */
            TOTAL_FREE_BLOCKS--;
            goto return_address;
        }
        
    }

/* if we get here it means that we have to allocate a new block */
reserve_new_block:

    /* do we have enough bytes left to use? if not allocate
     * more */
    if (BYTES_LEFT < (nbytes+sizeof(BLOCK_HEADER)))
    {
        /* get one page more */
        sbrk(PAGE_SIZE);

        /* we got more bytes for us */
        BYTES_LEFT += PAGE_SIZE;
    }

    /* our address will start at actual top
     * address */
    addr = (BLOCK_HEADER *) KMALLOC_TOP_ADDR;

    /* set malloc top address to new reserved area 
     * top address */
    KMALLOC_TOP_ADDR = (void *) (KMALLOC_TOP_ADDR+nbytes+sizeof(BLOCK_HEADER));
				
    /* this block is ours, let's initialize it and
     * use it */
    blk            = addr;
    BLOCK_FREE(blk)= FALSE;
    BLOCK_SIZE(blk)= nbytes;
    BLOCK_PREV(blk)= NULL;
    BLOCK_NEXT(blk)= NULL;

    /* we've used some bytes */
    BYTES_LEFT -= nbytes+sizeof(BLOCK_HEADER);
    
return_address:

    /* Return the pointer */
    return (unsigned *)(addr + sizeof(BLOCK_HEADER));

}

/* test speed */
int main(void)
{
	struct timeval t0, t1, tdiff;
	unsigned long i = MALLOCS;
	unsigned long *addr;

	while (i)
	{
		gettimeofday(&t0, NULL);
		addr=kmalloc(MALLOC_SIZE);
		//kfree(addr);
		gettimeofday(&t1, NULL);

		timersub(&t1, &t0, &tdiff);
		printf("%6ld %#.6f\n", MALLOCS-i, 0.0 +(tdiff.tv_sec + tdiff.tv_usec) * 1e-6 );
		i--;
	}
}

