/**************************************************************************************
 Copyright (c) 2002
      The UbixOS Project

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.24 2003/04/24 00:16:30 reddawg Exp $
**************************************************************************************/

#include <vmm/paging.h>
#include <vmm/memory.h>
#include <sys/idt.h>
#include <sys/gdt.h>
#include <ubixos/types.h>
#include <ubixos/schedule.h>
#include <ubixos/panic.h>
#include <lib/kmalloc.h>


uLong *pageDirectory = 0x0;
uLong memoryStart = 0x100000;
uLong *kernelPageDirectory = 0x0;

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

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

07/29/02 - I Started The Rewrite Of This Function Hopefully All Goes Well
           This Is The Startup Routine To Build The Initial VM Space.
           Also Note I May Switch The Page Fault To A Task Gate.

07/30/02 - I Decided That To Save On Performance All Page Tables Will Be
           Mapped In At BFC00000 So That Memory Does Not Need To Be Relocated
           To Alter Page Tables.
           Also Put Page Index At 0x100000
           
************************************************************************/
void initPagingSystem() {
  int i=0,x=0;
  uLong *pageTable;
  struct tssStruct *doubleFaultTSS = (struct tssStruct *)0x4000;
  //Allocate A Page For The Kernels VM Space Page Directory
  kernelPageDirectory = (uLong *)findFreePage(_current->id);
  //Make Sure The Page Directory Is Clean
  for (i=0;i<pageEntries;i++) {
    kernelPageDirectory[i] = (uLong)0x0;
    }
  //Allocate A Page For The First 4MB Of Memory
  pageTable = (uLong *)findFreePage(_current->id);
  kernelPageDirectory[0] = (uLong)((uLong)(pageTable) | pagePresent|pageWrite|pageUser);//pageDefault);
  //Make Sure The Page Table Is Clean
  for (i=0;i<pageEntries;i++) {
    pageTable[i] = (uLong)0x0;
    }
  //Map The First 1MB Of Memory To The Kernel VM Space
  for (i=0;i<(pageEntries/4);i++) {
    if ((i*0x1000) < 0xC0000) {
      pageTable[i] = (uLong)((i*0x1000) | pagePresent|pageWrite|pageUser);// pageDefault);
      }
    else {
      pageTable[i] = (uLong)((i*0x1000) | pagePresent|pageUser);// pageDefault);
      }
    }
  //Create Page Tables For The Top 1GB Of VM Space This Is To Be Shared With All VM Spaces
  for (i=768;i<pageEntries;i++) {
    pageTable = (uLong *)findFreePage(-1);
    //Make Sure The Page Table Is Clean
    for (x=0;x<pageEntries;x++) {
      pageTable[x] = (uLong)0x0;
      }
    //Map In The Page Directory
    kernelPageDirectory[i] = (uLong)((uLong)(pageTable) | pagePresent|pageWrite|pageUser);//pageDefault);
    }
  //Set Up Memory To Be All The Allocated Page Directories
  pageTable = (uLong *)findFreePage(-1);
  kernelPageDirectory[767] = ((uLong)pageTable | pagePresent|pageWrite|pageUser);//pageDefault);
  for (i=0;i<pageEntries;i++) {
    pageTable[i] = kernelPageDirectory[i];
    }
  //Also Set Up Page Directory To Be The The First Page In 0xE0400000
  pageTable = (uLong *)(kernelPageDirectory[0] & 0xFFFFF000);
  pageTable[256] = (uLong)((uLong)(kernelPageDirectory) | pagePresent|pageWrite|pageUser);//pageDefault);
  //Now Lets Turn On Paging With This Initial Page Table
  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" ((uLong *)(kernelPageDirectory))
    );
  //Now Add The IDT Entry For Page Faults
  setVector(_pageFault,14,dPresent + dInt + dDpl3);
  //Remap The Memory List
  for (i=0x101000;i<=(0x101000+(numPages*sizeof(mMap)));i+=0x1000) {
    remapPage(i,(0xE6667000+(i-0x101000)));
    }
  memoryMap = (mMap *)0xE6667000;

  doubleFaultTSS->back_link    = 0x0;
  doubleFaultTSS->esp0         = (uInt32)kmalloc(4096,-2)+4095;
  doubleFaultTSS->ss0          = 0x10;
  doubleFaultTSS->esp1         = 0x0;
  doubleFaultTSS->ss1          = 0x0;
  doubleFaultTSS->esp2         = 0x0;
  doubleFaultTSS->ss2          = 0x0;
  doubleFaultTSS->cr3          = (unsigned int)kernelPageDirectory;
  doubleFaultTSS->eip          = (unsigned int)&doubleFault;
  doubleFaultTSS->eflags       = 0x206;
  doubleFaultTSS->esp          = 0x1BFFF;
  doubleFaultTSS->ebp          = 0x1BFFF;
  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 = 0x0000;
  doubleFaultTSS->io_map       = 0x8000;
    
  }

void *mapFromTask(pidType pid,void *ptr,uInt32 size) {
  kTask_t *child = 0x0;
  uLong i = 0x0,x = 0x0,y = 0x0,count = ((size+4095)/0x1000),c = 0x0;
  uShort dI = 0x0,tI = 0x0;
  uInt32 baseAddr = 0x0,offset = 0x0;
  uInt32 *childPageDir   = (uInt32 *)0x5A00000;
  uInt32 *childPageTable = 0x0;
  uInt32 *pageTableSrc   = 0x0;
  offset = (uInt32)ptr & 0xFFF;
  baseAddr = (uInt32)ptr & 0xFFFFF000;
  child = getTask(pid);
  //Calculate The Page Table Index And Page Directory Index
  dI = (baseAddr/(1024*4096));
  tI = ((baseAddr-(dI*(1024*4096)))/4096);
  remapPage(child->tss.cr3,0x5A00000);
  for (i=0;i<0x1000;i++) {
    remapPage(childPageDir[i],0x5A01000 + (i * 0x1000));
    }
  for (x=(_current->oInfo.vmStart/(1024*4096));x<1024;x++) {
    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) {
        if (count > 1) {
          for (c=0;((c<count) && (y+c < 1024));c++) {
            if ((uInt32)pageTableSrc[y+c] != (uInt32)0x0) {
              c = -1;
              break;
              }
            }
          if (c != -1) {
            for (c=0;c<count;c++) {
              if ((tI + c) >= 0x1000) {
                dI++;
                tI = 0-c;
                }
              childPageTable = (uInt32 *)(0x5A01000 + (0x1000 * dI));
              remapPage(childPageTable[tI+c],((x*(1024*4096))+((y+c)*4096)));
              }
            unmapPage(0x5A00000,1);
            for (i=0;i<0x1000;i++) {
              unmapPage((0x5A01000 + (i*0x1000)),1);
              }
            return((void *)((x*(1024*4096))+(y*4096)+offset));
            }
          }
        else {
          //Map A Physical Page To The Virtual Page
          childPageTable = (uInt32 *)(0x5A01000 + (0x1000 * dI));
          remapPage(childPageTable[tI],((x*(1024*4096))+(y*4096)));
          //Return The Address Of The Mapped In Memory
          unmapPage(0x5A00000,1);
          for (i=0;i<0x1000;i++) {
            unmapPage((0x5A01000 + (i*0x1000)),1);
            }
          return((void *)((x*(1024*4096))+(y*4096)+offset));
          }
        }
      }
    }
  return(0x0);
  }

void unmapPages(void *ptr,uInt32 size) {
  uInt32 baseAddr = (uInt32)ptr & 0xFFFFF000;
  uInt32 dI = 0x0,tI = 0x0;
  uInt32 y = 0x0;
  uInt32 *pageTable = 0x0;
  
  dI = (baseAddr/(1024*4096));
  tI = ((baseAddr-(dI*(1024*4096)))/4096);  
  pageTable = (uInt32 *)(tablesBaseAddress + (4096*dI));
  for (y=tI;y<(tI+((size+4095)/4096));y++) {
    pageTable[y] = 0x0;
    }
  return;
  }
