#include "Paging.h"
#include "Console.h"
#include "Memory.h"

#define IndexFromBit(a) (a / (8 * 4))
#define OffsetFromBit(a) (a % (8 * 4))
#define PagePresent 0x1
#define PageReadWrite 0x2
#define PageSupervisor 0x0
#define PageUser 0x4

static Paging *instance;
void pageFault(struct registers regs);
void pageFault(struct registers regs)
{
	extern int *end;
	uint kernelEnd = (uint)&end;
	uint CR0 = 0;
	//No CR1; it's reserved
	uint faultingAddress = 0;
	uint CR3 = 0;
	uint CR4 = 0;
	uint SS = 0;
	asm volatile ("mov %%cr0, %0" : "=r"(CR0));
	asm volatile ("mov %%cr2, %0" : "=r"(faultingAddress));
	asm volatile ("mov %%cr3, %0" : "=r"(CR3));
	asm volatile ("mov %%cr4, %0" : "=r"(CR4));
	asm volatile ("mov %%ss, %0" : "=r"(SS));
	Console* console = Console::GetInstance();
	bool present = !(regs.err_code & 0x1);	// Page not present
	bool rw = regs.err_code & 0x2;			// Write operation?
	bool us = regs.err_code & 0x4;			// Processor was in user-mode?
	bool reserved = regs.err_code & 0x8;	// Overwritten CPU-reserved bits of page entry?
	bool id = regs.err_code & 0x10;			// Caused by an instruction fetch?

	console->ClearConsole();
	console->WriteLine("A page fault exception has ocurred. The details are displayed below:");
	console->Write("\tPage present: ");
	console->WriteLine((present ? "yes" : "no"));
	if(rw)
		console->WriteLine("\tOccured during a memory writing operation");
	else
		console->WriteLine("\tOccured during a memory reading operation");

	if(us)
		console->WriteLine("\tOcurred in user mode");
	else
		console->WriteLine("\tOcurred in supervisor mode");

	if(reserved)
		console->WriteLine("\tOverwrote data reserved by CPU");

	if(id)
		console->WriteLine("\tCaused by an instruction fetch");
	console->Write("\tOcurred at memory address ");
	console->WriteHexadecimal(faultingAddress);
	console->WriteLine();
	console->Write("\tEnd of kernel is ");
	console->WriteHexadecimal((uint)&end);
	console->WriteLine();
	console->Write("\tRegisters: ");
	console->WriteLine();
	console->Write("\t\tCR0: ");
	console->WriteHexadecimal(CR0);
	console->WriteLine();
	console->WriteLine("\t\tCR1: reserved (should always be 0x0)");
	console->Write("\t\tCR2: ");
	console->WriteHexadecimal(faultingAddress);
	console->WriteLine();
	console->Write("\t\tCR3: ");
	console->WriteHexadecimal(CR3);
	console->WriteLine();
	console->Write("\t\tCR4: ");
	console->WriteHexadecimal(CR4);
	console->WriteLine();
	console->Write("\t\tSS: ");
	console->WriteHexadecimal(SS);
	if(kernelEnd != MemoryAccess::GetPlacementAddress())
	{
		console->WriteLine();
		console->Write("\t");
		console->WriteHexadecimal(MemoryAccess::GetPlacementAddress() - kernelEnd);
		console->WriteLine(" bytes of memory have been allocated");
	}
	for(; ;)
		;
}
Paging::Paging()
{
}
Paging::~Paging()
{
}
Paging *Paging::GetInstance()
{

	if(!instance)
	{
		instance = new Paging();
		instance->InitialisePaging();
	}
	return instance;
}
Paging *Paging::GetInstance(uint upperMemory)
{
	if(!instance)
	{
		instance = new Paging();
		instance->InitialisePaging(upperMemory);
	}
	return instance;
}
void Paging::setFrame(uint address)
{
	uint frame = address / 0x1000;
	uint idx = IndexFromBit(frame);
	uint offset = OffsetFromBit(frame);

	frames[idx] |= (0x1 << offset);
}

void Paging::clearFrame(uint address)
{
	uint frame = address / 0x1000;
	uint idx = IndexFromBit(frame);
	uint offset = OffsetFromBit(frame);

	frames[idx] &= ~(0x1 << offset);
}

uint Paging::testFrame(uint address)
{
	uint frame = address / 0x1000;
	uint idx = IndexFromBit(frame);
	uint offset = OffsetFromBit(frame);

	return (frames[idx] & (0x1 << offset));
}

int Paging::firstFreeFrame()
{
	for(uint i = 0; i < IndexFromBit(nFrames); i++)
	{
		if(frames[i] != 0xFFFFFFFF)
		{
			for(int j = 0; j < 32; j++)
			{
				uint toTest = 0x1 << j;

				if(!(frames[i] & toTest))
					return i * 4 * 8 + j;
			}
		}
	}
	return -1;
}

void Paging::AllocateFrame(Page *pg, bool kernelMode, bool readWrite)
{
	if(pg->FrameAddress != 0)
		return;
	else
	{
		int idx = firstFreeFrame();

		if(idx != -1)
		{
			setFrame(idx * 0x1000);
			pg->Present = true;
			pg->ReadWrite = readWrite;
			pg->UserMode = !kernelMode;
			pg->FrameAddress = idx;
		}
		else
		{
			Console *panicConsole = Console::GetInstance();

			panicConsole->Panic(__LINE__, __FILE__, "no free pages have been found");
		}
	}
}
void Paging::FreeFrame(Page *pg)
{
	uint frame = pg->FrameAddress;

	if(!frame)
		return;
	else
	{
		clearFrame(frame);
		pg->FrameAddress = 0x0;
	}
}

void Paging::InitialisePaging()
{
	InitialisePaging(0x1000000);
}
void Paging::InitialisePaging(uint memorySize)
{
	asm volatile ("cli");
	uint memLength = memorySize - (memorySize % 0x1000);
	uint i = 0;
	
	nFrames = memLength / 0x1000;
	frames = (uint *)this->AllocateMemory(IndexFromBit(nFrames), false);//AllocateMemory is the problem. Memory is allocated from the stack, 
	MemoryAccess::SetMemory(frames, 0, IndexFromBit(nFrames));			//and is zeroed out here. Invalid opcode and/or corrupted stack results

	kernelDirectory = (PageDirectory *)this->AllocateMemory(sizeof(PageDirectory), true);
	MemoryAccess::SetMemory(kernelDirectory, 0, sizeof(PageDirectory));
	currentDirectory = kernelDirectory;

	while(i < MemoryAccess::GetPlacementAddress() + 0x1000)					//I've used a while loop because a for-loop caches placementAddress
	{																		//which is changed by memory allocations in the normal memory block
		AllocateFrame(GetPage(i, true, kernelDirectory), false, false);
		i += 0x1000;
	}
	ISR::RegisterExceptionHandler(14, &pageFault);
	SwitchPageDirectory(kernelDirectory);
	asm volatile ("sti");
}
void Paging::SwitchPageDirectory(PageDirectory *newDirectory)
{
	currentDirectory = newDirectory;
	asm volatile ("mov %0, %%CR3" : : "r" (&newDirectory->PhysicalAddress));
	uint CR0;
	asm volatile ("mov %%CR0, %0" : "=r" (CR0));
	CR0 |= 0x80000000;
	asm volatile ("mov %0, %%CR0" : : "r" (CR0));
}
Page *Paging::GetPage(uint address, bool make, PageDirectory *directory)
{
	address /= 0x1000;
	uint tableIndex = address / 1024;

	if(directory->Tables[tableIndex])
		return &directory->Tables[tableIndex]->Pages[address % 1024];
	else if(make)
	{
		uint physicalAddress;

		//directory->Tables[tableIndex] = (PageTable *)AllocateMemory(sizeof(PageTable), true, &physicalAddress);
		directory->Tables[tableIndex] = (PageTable *)MemoryAccess::AllocatePageAlignedMemory(sizeof(PageTable), &physicalAddress);
		MemoryAccess::SetMemory(directory->Tables[tableIndex], 0, 4096);
		directory->PhysicalAddress = physicalAddress | PagePresent | PageReadWrite | PageUser;
		return &directory->Tables[tableIndex]->Pages[address % 1024];
	}
	else
	{
		return 0;
	}
}

uint *Paging::AllocateMemory(uint size, bool pageAlign)
{
	if(pageAlign)
		return (uint *)MemoryAccess::AllocatePageAlignedMemory(size);
	else
		return (uint *)MemoryAccess::AllocateMemory(size);
}
uint *Paging::AllocateMemory(uint size, bool pageAlign, uint *physicalAddress)
{
	if(pageAlign)
		return (uint *)MemoryAccess::AllocatePageAlignedMemory(size, physicalAddress);
	else
		return (uint *)MemoryAccess::AllocateMemory(size, physicalAddress);
}
void Paging::Free(void *p)
{
	MemoryAccess::Free(p);
}
