/**************************************************************************************
 Copyright (c) 2002 The UbixOS Project
 All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors
in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project nor the names of its
contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 $Id: paging.c,v 1.1 2003/01/10 18:33:01 reddawg Exp $

**************************************************************************************/

#include <vmm/paging.h>
#include <vmm/memory.h>
//#include <lib/kstdio.h>
#include <ubixos/kpanic.h>
#include <ubixos/vitals.h>
#include <ubixos/schedule.h>
#include <ubixos/idt.h>
#include <ubixos/tss.h>
//#include <drivers/display.h>

uInt32 *kernelPageDirectory = NULL;

/************************************************************************

Function: void initPageSystem()
Description: This Function Will Initialize The Ubix Paging Sytem
Notes:

************************************************************************/
void initPagingSystem() {
  int i = 0x0,x = 0x0;
  uInt32 *tempPageTable = 0x0;
  struct tssStruct *doubleFaultTSS = (struct tssStruct *)0x1000;
  //kprintf("Initializing Paging System......... ");
  if (!(kernelPageDirectory = (uInt32 *)findFreePage(-1))) {
    kPanic("Error Initializing Paging System\n");
    }
  //Null Out The Page Directory
  for (i=0x0;i<pageEntries;i++) {
    kernelPageDirectory[i] = 0x0;
    }
  //Set Up A Page Table For The First 4MB The First 1MB Is 1:1
  if (!(tempPageTable = (uInt32 *)findFreePage(-1))) {
    kPanic("Error Initializing Paging System\n");
    }
  //Null Out the Page Table
  for (i=0x0;i<pageEntries;i++) {
    tempPageTable[i] = (uInt32)0x0;
    }
  //Set Up The First Meg Of The Page Table To Be 1:1
  for (i=0x0;i<(pageEntries);i++) {
    tempPageTable[i] = (uInt32)((uInt32)(i * 0x1000) | pageDefault);
    }
  //Setup 0x101000 To Be Our Page Directory
  tempPageTable[256] = (uInt32)((uInt32)(kernelPageDirectory) | pageDefault);
  //Insert New Page Table Into Directory
  kernelPageDirectory[0] = (uInt32)((uInt32)(tempPageTable) | pageDefault);
  /*
  Now That We Have The Lower 1MB Mapped 1:1 Lets Map In Tables For The Top 1GB
  This Space As Well As The Lower 1MB Will Be Shared With All The Applications
  */
  for (i=768;i<pageEntries;i++) {
    if(!(tempPageTable = (uInt32 *)findFreePage(-1))) {
      kPanic("Error Initializing Paging System\n");
      }
    //Null Out The Page Table
    for (x=0x0;x<pageEntries;x++) {
      tempPageTable[x] = (uInt32)0x0;
      }
    //Map The New Page Table To The Page Directory
    kernelPageDirectory[i] = (uInt32)((uInt32)(tempPageTable) | pageDefault);
    }
  /*
  We Will Now Use Page Directory 767 To Hold All The Page Tables So We Don't
  Need To Remap Them In To Modify Them
  */
  if (!(tempPageTable = (uInt32 *)findFreePage(-1))) {
    kPanic("Error Initializing Paging System\n");
    }
  kernelPageDirectory[767] = (uInt32)((uInt32)tempPageTable | pageDefault);
  for (i=0x0;i<pageEntries;i++) {
    tempPageTable[i] = kernelPageDirectory[i];
    }
  /*
  Now That We Have A Virtual Memory Map Set Up Lets Turn On Paging Hopefully
  All Goes Well
  */
  asm(
    "movl %0,%%eax          \n"
    "movl %%eax,%%cr3       \n"
    "movl %%cr0,%%eax       \n"
    "orl  $0x80010000,%%eax \n" //Flags To Enable Paging With Protection
    "movl %%eax,%%cr0       \n"
    : : "d" ((uInt32)(kernelPageDirectory))
    );
  //Remap The Vitals Page
  remapPage(0x100000,0xC0000000,-1);
  //Remap The Pages For The Memory Array
  systemVitals = (struct vitalsStruct *)0xC0000000;
  for (i=0x101000;i<=(0x101000+(systemVitals->numPages*sizeof(struct memMap)));i+=0x1000) {
    remapPage(i,(0xC0001000+(i-0x101000)),-1);
    }
  memoryMap = (struct memMap *)0xC0001000;
  doubleFaultTSS->back_link    = 0x0;
  doubleFaultTSS->esp0         = 0x9000;
  doubleFaultTSS->ss0          = 0x10;
  doubleFaultTSS->esp1         = 0x8000;
  doubleFaultTSS->ss1          = 0x58;
  doubleFaultTSS->esp2         = 0x7000;
  doubleFaultTSS->ss2          = 0x48;
  doubleFaultTSS->cr3          = (unsigned int)kernelPageDirectory;
  doubleFaultTSS->eip          = (unsigned int)&doubleFault;
  doubleFaultTSS->eflags       = 0x206;
  doubleFaultTSS->esp          = 0x6FFF;
  doubleFaultTSS->ebp          = 0x6FFF;
  doubleFaultTSS->esi          = 0x0;
  doubleFaultTSS->edi          = 0x0;
  doubleFaultTSS->es           = 0x10;
  doubleFaultTSS->cs           = 0x08;
  doubleFaultTSS->ss           = 0x10;
  doubleFaultTSS->ds           = 0x10;
  doubleFaultTSS->fs           = 0x10;
  doubleFaultTSS->gs           = 0x10;
  doubleFaultTSS->ldt          = 0x0;
  doubleFaultTSS->trace_bitmap = 0x80000000;
  //kprintf("INITIALIZED\n");
  return;
  }

/************************************************************************

Function: void remapPage(Physical Source,Virtual Destination,Proccess ID)
Description: This Function Will Remap A Physical Page Into Virtual Space
Notes:

07/29/02 - Rewrote This To Work With Our New Paging System

07/30/02 - Changed Address Of Page Tables And Page Directory

************************************************************************/
void remapPage(uInt32 sourceAddr,uInt32 destAddr,pidType pid) {
  uInt16 destPageDirectoryIndex=0,destPageTableIndex=0;
  uInt32 *pageDir,*pageTable;
  //Set Pointer pageDirectory To Point To The Virtual Mapping Of The Page Directory
  pageDir = (uInt32 *)directoryBaseAddress;
  //Check To See If Page Table Exists
  destPageDirectoryIndex = (destAddr/(1024*4096));
  if (pageDir[destPageDirectoryIndex] == 0) {
    //If Page Table Is Non Existant Then Set It Up
    pageDir[destPageDirectoryIndex] = (uInt32)findFreePage(pid) | pageDefault;
    //Also Add It To Virtual Space So We Can Make Changes Later
    pageTable = (uInt32 *)(tablesBaseAddress + (4096 * 767));
    pageTable[destPageDirectoryIndex] = pageDir[destPageDirectoryIndex];
    //Reload Page Directory
    asm(
      "movl %cr3,%eax\n"
      "movl %eax,%cr3\n"
      );
    }
  //Set Address To Page Table
  pageTable = (uInt32 *)(tablesBaseAddress + (4096 * destPageDirectoryIndex));
  //Get The Index To The Page Table
  destPageTableIndex = ((destAddr-(destPageDirectoryIndex*(1024*4096)))/4096);
  //If The Page Is Mapped In Free It Before We Remap
  if (pageTable[destPageTableIndex] > 0) {
    //Clear The Page First For Security Reasons
    freePage(((uInt32)pageTable[destPageTableIndex] & 0xFFFFF000));
    }
  //Set The Source Address In The Destination
  pageTable[destPageTableIndex] = (uInt32)(sourceAddr | pageDefault);
  //Reload The Page Table;
  asm(
    "movl %cr3,%eax\n"
    "movl %eax,%cr3\n"
    );
  //Return
  return;
  }

/************************************************************************

Function: void pageFault();
Description: This Function Is The Second Half Of The Page Fault ISR
             Currently It Handles COW However I Need To Prepar It For
             Swapping
Notes:

************************************************************************/
void pageFault() {
  uInt32 cr2 = 0x0;
  asm("movl %%cr2,%0": "=g" (cr2));
  //printColor = 0x9C;
  //kprintf("PAGE FAULT - Task ID: %i, Memory Address: 0x%X\n",_current->id,cr2);
  //printColor = defaultColor;
//  setTaskStatus(_current->id, EMPTY);
  _current->status = EMPTY;
  schedule();
  return;
  }

/************************************************************************

Function: void pageFaultISR()
Description: This Is The ASM Code That Calls The pageFault() Function
Notes:

************************************************************************/
asm(
    ".global pageFaultISR\n"
    "pageFaultISR:       \n"
    "xchgl %eax,(%esp)   \n"
    "pushl %ecx          \n"
    "pushl %edx          \n"
    "push %ds            \n"
    "push %es            \n"
    "push %fs            \n"
    "call pageFault      \n"
    "pop %fs             \n"
    "pop %es             \n"
    "pop %ds             \n"
    "popl %edx           \n"
    "popl %ecx           \n"
    "popl %eax           \n"
    "iret                \n"
    );

/************************************************************************

Function: void *getFreeKernelPage(pidType pid);
Description: Returns A Free Page Mapped To The VM Space
Notes:

07/30/02 - This Returns A Free Page In The Top 1GB For The Kernel

************************************************************************/
void *getFreeKernelPage(pidType pid) {
  int x=0,y=0;
  uInt32 *pageTableSrc = 0x0;
  //Lets Search For A Free Page
  for (x=768;x<1024;x++) {
    //Set Page Table Address
    pageTableSrc = (uInt32 *)(tablesBaseAddress + (4096*x));
    for (y=0;y<1024;y++) {
      //Loop Through The Page Table Find An UnAllocated Page
      if ((uInt32)pageTableSrc[y] == (uInt32)0x0) {
        //Map A Physical Page To The Virtual Page
        remapPage((uInt32)findFreePage(pid),((x*(1024*4096))+(y*4096)),pid);
        //Clear This Page So No Garbage Is There
        clearVirtualPage((uInt32)((x*(1024*4096))+(y*4096)));
        //Return The Address Of The Newly Allocate Page
        return((void *)((x*(1024*4096))+(y*4096)));
        }
      }
    }
  //If No Free Page Was Found Return NULL
  return(0x0);
  }

/************************************************************************

Function: void clearVirtualPage(uInt32 pageAddr);
Description: This Will Null Out A Page Of Memory
Notes:

************************************************************************/
void clearVirtualPage(uInt32 pageAddr) {
  uInt32 *src = 0x0;
  int counter = 0x0;
  //Set Source Pointer To Virtual Page Address
  src = (uInt32 *)pageAddr;
  //Clear Out The Page
  for (counter=0;counter<pageEntries;counter++) {
    (uInt32)src[counter] = (uInt32)0x0;
    }
  //Return
  return;
  }

/************************************************************************

Function: void doubleFault();
Description: This Function Is The Double Fault Handler
Notes:

************************************************************************/
void doubleFault() {
  //printColor = 0x9C;
  //kprintf("DOUBLEFAULT - Task Id: %i, Instruction Address: 0x%X, ESP Address: 0x%X\n",_current->id,_current->tss.eip,_current->tss.esp);
  //printColor = defaultColor;
  //Real Clean Up Code Should Go Here
  _current->status = EMPTY;
  _current->tss.esp = 0x1FFF;
  _current->tss.eip = (uInt32)&schedule;
  asm(
    "pusha\n"
    "iret \n"
    );
  return;
  }

/************************************************************************

Function: void doubleFaultCleanUp();
Description: This Function Will Clean Up The Double Fault TSS
Notes:

************************************************************************/
void doubleFaultCleanUp() {
  struct tssStruct *doubleFaultTSS = (struct tssStruct *)0x1000;
  //This Fixes The Double Fault TSS So It Enters Correctly
  doubleFaultTSS->eip          = (unsigned int)&doubleFault;
  doubleFaultTSS->esp          = 0x6FFF;
  doubleFaultTSS->ebp          = 0x6FFF;
  schedule();
  return;
  }

/************************************************************************

Function: void createVirtualMemorySpace();
Description: This will create an empty vm space for task
Notes:

************************************************************************/
void createVirtualMemorySpace(pidType pid) {
  uInt16 i = 0x0;
  uInt32 *newPageDirectory = 0x0;
  if (!(newPageDirectory = (uInt32 *)findFreePage(pid))) {
    kPanic("Error Initializing Paging System\n");
    }
  newPageDirectory = findFreePage(_current->id);
  newPageDirectory[0] = kernelPageDirectory[0];
  for (i=768;i<1024;i++) {
    newPageDirectory[i] = kernelPageDirectory[i];
    }
  }

/************************************************************************

Function: void *copyVirtualSpace(pidType pid)
Description: This will create a copy of the current virtual space
Notes:

************************************************************************/  
void *copyVirtualSpace(pidType pid) {
  uInt32 *newPageDirectory        = 0x0;
  uInt32 *newPageDirectoryAddress = 0x0;
  uInt32 *parentPageDirectory     = 0x0;
  uInt32 *parentPageTable         = 0x0;
  uInt32 *parentStackPage         = 0x0;
  int    i                        = 0x0;
  //Allocate Page For New Directory
  if ((newPageDirectory = getFreeKernelPage(pid)) == 0x0) {
    //If Allocation Fails Return NULL
    return(0x0);
    }
  //Set Point For Parent Page Directory
  parentPageDirectory = (uInt32 *)directoryBaseAddress;
  //Flush New Page Directory
  for (i=0;i<pageEntries;i++) {
    newPageDirectory[i] = (uInt32)0x0;
    }
  //Map The Top 1GB Region Of The VM Space
  for (i=768;i<pageEntries;i++) {
    newPageDirectory[i] = parentPageDirectory[i];
    }
  return(newPageDirectory);
  }
