#include <stdio.h>
#include <stdlib.h>

#ifndef _c_arch_kernel_vmm
#define _c_arch_kernel_vmm

/* z2arch conceptual kernelspace memory management, layer 1.
   Layer 1's responsibility is to provide a mechanism for Layer 2
   to acquire blocks of memory that will not result in
   kernelspace becoming fragmented ... and to do that quickly.

   Layer 2 (z2arch-abm) allows the kernel to allocate blocks of
   arbitrary size. It is Layer 2's responsibility to nullify the
   internal fragmentation prevalent in buddy allocators.

   Also, keep in mind ... This is CONCEPTUAL and as such, is yet to
   be integrated (or indeed, even tested...) with z2arch. 

   Keep in mind when messing with this code, that z2's kernelspace is
   only ever able to expand to a total size of 8MiB. It is designed to
   take as little space as possible. 

   If youre looking for an implementation of the AVL Data structure, that
   actually uses pointers (Ah, We love pointers...), email me and Ill flick you
   some C source :) 

   Author  : DG.Ward (aka: Zeii, ~elderK, Zit the Interdimensional Tinker)
   Contact : warddg1@tekotago.ac.nz, comeherenightmare@hotmail.com, kyretzn@gmail.com
   Date    : 10/11/07
   Version : 0A

   ... Also, as a note to anyone wishing to use this code ...
   You are free to use this code, in anyway you see fit... provided you give me the
   credit I deserve. You must keep my contact information in the source... Any issues
   with that, email me...

*/

enum {__INSERTION, __DELETION};
enum {__LEFT, __RIGHT, __PARENT, __NULL=0x800};
enum {__LEAF, __BRANCH, __SUBTREE};
enum {__LEFT_CRITICAL, __LEFT_HEAVY, __BALANCED, __RIGHT_HEAVY, __RIGHT_CRITICAL};
enum {__4KiB, __8KiB, __16KiB, __32KiB, __64KiB, __128KiB, __256KiB, __512KiB, __1MiB, __2MiB, __4MiB, __8MiB};

unsigned char direct_constants[2] = {__RIGHT_HEAVY, __LEFT_HEAVY};

unsigned char indirect_constants[2][2] =
	{
		{__LEFT_HEAVY, __RIGHT_HEAVY},
		{__RIGHT_HEAVY, __LEFT_HEAVY}
	};

unsigned char indirect_balances[2][4] =
	{
		{__BALANCED, __RIGHT_HEAVY, __LEFT_HEAVY, __BALANCED},
		{__BALANCED, __LEFT_HEAVY, __RIGHT_HEAVY, __BALANCED}
	};

unsigned char trace_constants[2] = {-1, +1};

union block_t {
	unsigned long long int _raw; /* _raw is used to quickly initialize all properties to zero. */
	struct {
		/* Node references, _lref/_rref/_uref link to other nodes via
           storing direct array indices. Values $0 through $7FF are valid
		   array subscripts. The value $800 is used to signal a NULL link. */ 
		unsigned int _lref:12;
		unsigned int _rref:12;
		unsigned int _bksz:4;	/* Size Modifier. Size = 2^(12+_bksz). A modifier of
								   zero selects a block size of 4KiB (2^(12+0)).
								   Values 0 through 11 are valid. */ 
		unsigned int _bkbl:3;	/* Node balance, required by the AVL structure.
								   Values 0 through 4 are valid. */
		unsigned int _bkrl:1;	/* Node relationship, used to signal whether the
								   node is a left or right child. */ 
		unsigned int _uref:12;
		unsigned int _addr:20;	/* Address of region that the block governs,
								   4KiB minimum addressable unit. */
	} _data;
} __attribute__((packed));

struct block_tree_t {
	unsigned short _available;	/* _available and _allocated identify the */
	unsigned short _allocated; 	/* root node via array index. */ 
}; 

#define REF_ID		unsigned char
#define BLOCK_ID	unsigned short
#define BLOCK_T		union block_t
#define BLOCK_PTR_T	BLOCK_T *
#define TREE_T		struct block_tree_t
#define TREE_PTR_T	TREE_T *
#define TREE_LNK_T	unsigned short *

BLOCK_PTR_T node_space = 0;
BLOCK_ID	node_stack = 0;
TREE_T		node_trees[12];

void set_reference(BLOCK_ID owner, REF_ID select, BLOCK_ID target) {
	switch(select) {
		case __LEFT:	node_space[owner]._data._lref = target; return;
		case __RIGHT:	node_space[owner]._data._rref = target; return;
		case __PARENT:	node_space[owner]._data._uref = target; return;
		default: 		return;
	}
}

BLOCK_ID get_reference(BLOCK_ID block, REF_ID select) {
	switch(select) {
		case __LEFT:	return node_space[block]._data._lref;
		case __RIGHT:	return node_space[block]._data._rref;
		case __PARENT:	return node_space[block]._data._uref;
		default:		return __NULL;
	}
}

BLOCK_ID rotate_subtree(TREE_LNK_T tree, BLOCK_ID subtree, unsigned char direction) {
	BLOCK_ID direct_child = get_reference(subtree, !direction);
	set_reference(subtree, !direction, get_reference(direct_child, direction)); 
	set_reference(direct_child, direction, subtree);

	node_space[direct_child]._data._uref = node_space[subtree]._data._uref;
	node_space[direct_child]._data._bkrl = node_space[subtree]._data._bkrl;

	if(*tree == subtree) *tree = direct_child;
	
	node_space[subtree]._data._bkrl = direction;
	set_reference(subtree, __PARENT, direct_child);	

	if(get_reference(subtree, !direction) != __NULL) {
		node_space[get_reference(subtree, !direction)]._data._bkrl = !direction;
		node_space[get_reference(subtree, !direction)]._data._uref = subtree;
	}

	return direct_child;
}

BLOCK_ID rebalance_subtree(TREE_LNK_T tree, BLOCK_ID subtree) {
	unsigned char imbalance_class = node_space[subtree]._data._bkbl > __BALANCED;
	BLOCK_ID direct_child = get_reference(subtree, imbalance_class);

	if(node_space[direct_child]._data._bkbl == direct_constants[imbalance_class]) {
		BLOCK_ID indirect_child = get_reference(direct_child, !imbalance_class);

		if(node_space[indirect_child]._data._bkbl == indirect_constants[imbalance_class][0]) {
			node_space[direct_child]._data._bkbl = indirect_balances[imbalance_class][0];
			node_space[subtree]._data._bkbl = indirect_balances[imbalance_class][1];
		} else if(node_space[indirect_child]._data._bkbl == indirect_constants[imbalance_class][1]) {
			node_space[direct_child]._data._bkbl = indirect_balances[imbalance_class][2];
			node_space[subtree]._data._bkbl = indirect_balances[imbalance_class][3];
		} else node_space[subtree]._data._bkbl = node_space[direct_child]._data._bkbl = __BALANCED; 

		node_space[indirect_child]._data._bkbl = __BALANCED;
		set_reference(subtree, imbalance_class, rotate_subtree(tree, direct_child, imbalance_class));
	} else if(node_space[direct_child]._data._bkbl == direct_constants[!imbalance_class]) {
		node_space[direct_child]._data._bkbl = __BALANCED;
		node_space[subtree]._data._bkbl = __BALANCED;
	} else if(node_space[direct_child]._data._bkbl == __BALANCED) {
		node_space[direct_child]._data._bkbl = direct_constants[imbalance_class];
		node_space[subtree]._data._bkbl = direct_constants[!imbalance_class];
	}
	return rotate_subtree(tree, subtree, !imbalance_class);
}

void trace_subtree(TREE_LNK_T tree, BLOCK_ID origin, unsigned char mode) {
	if(origin != __NULL) {
		BLOCK_ID iterator = get_reference(origin, __PARENT);

		unsigned char relationship_cache = 0;
		signed char multiplier = mode ? -1 : 1;

		while(1) {
			relationship_cache = node_space[origin]._data._bkrl;

			switch(node_space[origin]._data._bkbl) {
				case __LEFT_CRITICAL:
				case __RIGHT_CRITICAL: {
					if(iterator == __NULL) *tree = rebalance_subtree(tree, origin);
					else {
						set_reference(iterator, relationship_cache, rebalance_subtree(tree, origin));
						if(mode && node_space[get_reference(iterator, relationship_cache)]._data._bkbl != __BALANCED) return;
					}
				}
				case __BALANCED: {
					if(mode) break;
				} return;
				default: {
					if(mode) return;
				} break; 
			}
			if(iterator != __NULL) {
				node_space[iterator]._data._bkbl += multiplier * trace_constants[relationship_cache];
				origin = iterator;
				iterator = get_reference(iterator, __PARENT);
			} else break;
		}
	}
}

BLOCK_ID insert(TREE_LNK_T tree, BLOCK_ID node) {
	/* Ensure that the node being inserted doesnt have a configuration that
       will seriously mess with insertion ... or rebalancing ... */
	/* (Nodes being inserted must have 'clean' references ...) */
	node_space[node]._data._lref =
	node_space[node]._data._uref =
	node_space[node]._data._rref = __NULL;

	node_space[node]._data._bkbl = __BALANCED;

	if(*tree == __NULL) {
		*tree = node;
	} else {
		BLOCK_ID iterator = *tree;
		unsigned char tracker = 0;

		while(1) {
			tracker = node_space[node]._data._addr > node_space[iterator]._data._addr;

			if(get_reference(iterator, tracker) != __NULL) iterator = get_reference(iterator, tracker);
			else {
				set_reference(iterator, tracker, node);
				break;
			}
		}
		node_space[node]._data._bkrl = tracker;
		set_reference(node, __PARENT, iterator);
		node_space[iterator]._data._bkbl += trace_constants[tracker];
		trace_subtree(tree, iterator, __INSERTION);
	}
	return 0;
}

BLOCK_ID delete(TREE_LNK_T tree, BLOCK_ID node) {
	if(*tree == node && get_reference(node, __LEFT) == __NULL &&
						get_reference(node, __RIGHT) == __NULL) {
		*tree = __NULL;
	} else {
		unsigned char node_class = 0;

		if(get_reference(node, __LEFT) != __NULL) node_class = 1;
		if(get_reference(node, __RIGHT) != __NULL) node_class++;

		switch(node_class) {
			case __SUBTREE: {
				BLOCK_ID iterator = get_reference(node, __LEFT);
				unsigned int addr_cache = 0;

				while(get_reference(iterator, __RIGHT) != __NULL)
					iterator = get_reference(iterator, __RIGHT);

				addr_cache = node_space[node]._data._addr;
				if(get_reference(iterator, __LEFT) != __NULL) {
					node_space[node]._data._addr = node_space[iterator]._data._addr;

					node_space[iterator]._data._addr =
						node_space[get_reference(iterator, __LEFT)]._data._addr;

					node_space[iterator]._data._bkbl++;
					iterator = get_reference(iterator, __LEFT);

					node_space[get_reference(iterator, __PARENT)]._data._lref = __NULL;
					node_space[iterator]._data._addr = addr_cache;
				} else {
					node_space[get_reference(iterator, __PARENT)]._data._bkbl +=
						trace_constants[!node_space[iterator]._data._bkrl];

					set_reference(get_reference(iterator, __PARENT), node_space[iterator]._data._bkrl, __NULL);
					node_space[node]._data._addr = node_space[iterator]._data._addr;

					node_space[iterator]._data._addr = addr_cache;
				}
				node = iterator;
			} break;

			case __BRANCH: {
				node_space[get_reference(node, node_space[node]._data._bkbl > __BALANCED)]._data._bkrl =
					node_space[node]._data._bkrl;

				node_space[get_reference(node, node_space[node]._data._bkbl > __BALANCED)]._data._uref =
					node_space[node]._data._uref;

				if(node_space[node]._data._uref != __NULL) {
					set_reference(get_reference(node, __PARENT), node_space[node]._data._bkrl,
											    get_reference(node, node_space[node]._data._bkbl > __BALANCED));	

					node_space[node_space[node]._data._uref]._data._bkbl += trace_constants[!node_space[node]._data._bkrl];
				} else *tree = get_reference(node, node_space[node]._data._bkbl > __BALANCED);
			} break;

			case __LEAF: {
				if(node_space[node]._data._uref != __NULL) {
					set_reference(node_space[node]._data._uref, node_space[node]._data._bkbl > __BALANCED, __NULL);
					node_space[node_space[node]._data._uref]._data._bkbl += trace_constants[!node_space[node]._data._bkrl];
				} else *tree = __NULL;
			} break;
		}
		trace_subtree(tree, get_reference(node, __PARENT), __DELETION);
	}
	return node;
}

BLOCK_ID pop_block(void) {
	BLOCK_ID popped_block = node_stack;
	if(node_stack != __NULL) node_stack = node_space[node_stack]._data._rref;
	return popped_block;
}

void push_block(BLOCK_ID block) {
	node_space[block]._data._rref = node_stack;
	node_stack = block;	
}

void debug_stack(void) {
	BLOCK_ID iterator = node_stack;
	while(iterator != __NULL) {
		printf(" :: %u -> %u\r\n", iterator, node_space[iterator]._data._rref); 
		iterator = node_space[iterator]._data._rref;
	}
}

unsigned char initialize(const void *addrsp_base, const void *nodesp_base) {
	if(nodesp_base) {
		node_space = (BLOCK_PTR_T)nodesp_base;
		node_stack = __NULL;	

		BLOCK_ID init_stack = 0;	
		for(; init_stack < __NULL; push_block(init_stack++));

		for(init_stack = 0; init_stack < 12; init_stack++)
			node_trees[init_stack]._available = node_trees[init_stack]._allocated = __NULL;
	
		init_stack = pop_block();
		node_space[init_stack]._data._bksz = __8MiB;
		node_space[init_stack]._data._addr = (unsigned int)addrsp_base >> 12;
		insert(&node_trees[11]._available, init_stack);

		return 1;
	} else return 0;
}

void *acquire(unsigned char size) {
	BLOCK_ID iterator = node_trees[size]._available;
	if(iterator != __NULL) {
		insert(&node_trees[size]._allocated, delete(&node_trees[size]._available, iterator));
	} else {
		unsigned char original_size = size;
	
		while(((iterator = node_trees[size]._available) == __NULL) && (size++ < 12));
		if(size == 12) return (void *)0x200;
		
		delete(&node_trees[size]._available, iterator);

		while(size != original_size) {
			BLOCK_ID chunk_iterator = pop_block();
			if(chunk_iterator == __NULL) return (void *)1;
			
			node_space[chunk_iterator]._data._addr =
				node_space[iterator]._data._addr + (1 << (--node_space[iterator]._data._bksz));	

			node_space[chunk_iterator]._data._bksz = node_space[iterator]._data._bksz;
			size--;
			insert(&node_trees[size]._available, chunk_iterator);
		}
		insert(&node_trees[original_size]._allocated, iterator);
	}	
	return (void *)(node_space[iterator]._data._addr << 12);
}

void release(const void *address) {
	unsigned int packed_address = (unsigned int)address >> 12, search_size = 0, search_path = 0;
	BLOCK_ID iterator = __NULL, buddy_iterator = __NULL;
	
	while(search_size < 12) {
		if((iterator = node_trees[search_size++]._allocated) != __NULL) {
			for(search_path = packed_address > node_space[iterator]._data._addr;
				packed_address != node_space[iterator]._data._addr && iterator != __NULL;
				search_path = packed_address > node_space[iterator]._data._addr,
				iterator = get_reference(iterator, search_path));

			if(iterator != __NULL) break; 
		}
	}
	delete(&node_trees[node_space[iterator]._data._bksz]._allocated, iterator);

	if(iterator != __NULL) { 
		while(node_space[iterator]._data._bksz < 11) {
			if((buddy_iterator = node_trees[node_space[iterator]._data._bksz]._available) != __NULL) { 
				packed_address = node_space[iterator]._data._addr ^ (1 << node_space[iterator]._data._bksz);

				for(search_path = packed_address > node_space[buddy_iterator]._data._addr;
					packed_address != node_space[buddy_iterator]._data._addr && buddy_iterator != __NULL;
					search_path = packed_address > node_space[buddy_iterator]._data._addr,
					buddy_iterator = get_reference(buddy_iterator, search_path));

				if(buddy_iterator != __NULL) {
					delete(&node_trees[node_space[iterator]._data._bksz]._available, buddy_iterator);

					if(node_space[iterator]._data._addr < node_space[buddy_iterator]._data._addr) {
						push_block(buddy_iterator);
					} else {
						push_block(iterator);
						iterator = buddy_iterator;	
					}
					node_space[iterator]._data._bksz++;
				} else break;
			} else break;
		}
		insert(&node_trees[node_space[iterator]._data._bksz]._available, iterator);
	}
}

#ifdef _test_akvm

	void show_tree(TREE_LNK_T tree, BLOCK_ID node) {
		if(node != __NULL) {
			if(get_reference(node, __LEFT) != __NULL) show_tree(tree, get_reference(node, __LEFT));

			printf("!%u! 0x%X (%u KiB)", node, node_space[node]._data._addr << 12,
				1 << (node_space[node]._data._bksz + 2));

			if(node != *tree) printf("< %u >", get_reference(node, __PARENT));

			printf("\r\n");

			if(get_reference(node, __RIGHT) != __NULL) show_tree(tree, get_reference(node, __RIGHT));
		}
	}

	int main(void) {
		/* allocate node space ... */
		node_space = (BLOCK_PTR_T)malloc(sizeof(BLOCK_T)*2048);
		/* init ... */
		initialize(0x0, node_space);

		/* Allocate all of memory ... */
		//printf("Fully subdividing all available memory ... ");
		//for(unsigned int a = 0; a < 0x800; a++) acquire(__4KiB);

		void *a = acquire(__256KiB);
		void *b = acquire(__256KiB);
		void *c = acquire(__256KiB);
		void *d = acquire(__512KiB);
		//printf("DONE\r\n");

		release(a);
		release(b);
		release(c);
		release(d);

		for(unsigned int i = 0; i < 12; i++) {
			printf("\r\nSIZE: %u kB\r\n", 1 << (i + 2));
			printf("ALLOC ------------------------------------ \r\n");
			show_tree(&node_trees[i]._allocated, node_trees[i]._allocated);
			printf("AVAIL ------------------------------------ \r\n");
			show_tree(&node_trees[i]._available, node_trees[i]._available);
		}
		free(node_space);
	
		return 0;
	}

#endif

#endif

