#include "assert.H"
#include "exceptions.H"
#include "console.H"
#include "paging_low.H"
#include "page_table.H"

PageTable * PageTable::current_page_table = NULL;
unsigned int PageTable::paging_enabled = 0;
ContFramePool * PageTable::kernel_mem_pool = NULL;
ContFramePool * PageTable::process_mem_pool = NULL;
unsigned long PageTable::shared_size = 0;



void PageTable::init_paging(ContFramePool * _kernel_mem_pool,
                            ContFramePool * _process_mem_pool,
                            const unsigned long _shared_size)
{
  kernel_mem_pool = _kernel_mem_pool;
  process_mem_pool = process_mem_pool;
  shared_size = _shared_size;
  
  Console::puts("\nInitialized Paging System\n");
}

PageTable::PageTable()
{
  unsigned long * temp_page_directory = (unsigned long *) (4096 * kernel_mem_pool->get_frames(1)); // Getting frame address to assign to page directory. 
 
  unsigned long * page_table = (unsigned long *) (4096 * kernel_mem_pool->get_frames(1)); // Get another frame for the page table.

  unsigned long tempaddr = 0; // Temporary address iterator.

  // We need to map the first 4MB.
  for(unsigned int i = 0; i < 1024; i++)
  {
    page_table[i] = tempaddr | 3; // set bits 0 and 1 to present and read/write respectively
    tempaddr += 4096; // 4096 = 4kb
  }
  

  // Fill first entry of page directory.
  temp_page_directory[0] = (unsigned long)page_table;
  temp_page_directory[0] = temp_page_directory[0] | 3;  

  for(unsigned int j = 1; j < 1024; j++)
  {
    temp_page_directory[j] = 0 | 2;
  }

  page_directory = temp_page_directory;

  current_page_table = this;

  Console::puts("\nConstructed Page Table object\n");
}


void PageTable::load()
{
  write_cr3((unsigned long)page_directory);
  current_page_table = this;
  Console::puts("\nLoaded page table\n");
}

void PageTable::enable_paging()
{
  write_cr3((unsigned long)current_page_table->page_directory);
  write_cr0(read_cr0() | 0x80000000);
  paging_enabled = read_cr0();
  Console::puts("\nEnabled paging\n");
}

void PageTable::handle_fault(REGS * _r)
{
  unsigned long temp_addr = (process_mem_pool->get_frames(1));
  ((unsigned long *) ((unsigned long *) current_page_table->page_directory)[0])[temp_addr] 
    = ((unsigned long *) ((unsigned long *) current_page_table->page_directory)[0])[temp_addr] | 3;

  Console::puts("\nerror code: ");
  Console::puti(_r->err_code);

  unsigned char mask = 0x00;
  read_cr2();
  
  Console::puts("\nhandled page fault\n");
}

