/**************************************************************************************
 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: memory.c,v 1.8 2003/05/11 23:37:07 reddawg Exp $

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

#include <vmm/memory.h>
#include <vmm/paging.h>
#include <sys/io.h>
#include <ubixos/types.h>
#include <ubixos/vitals.h>
#include <sys/video.h>

mMap *memoryMap = (mMap *) 0x101000;
int numPages = 0;
uInt32 freePages = 0;

int countMemory() {
  register unsigned long *mem;
  unsigned long memCount=-1, tempMemory;
  unsigned short  memKb=0;
  unsigned char   irq1State, irq2State;
  unsigned long cr0;
  /* Save States Of IRQ 1 & 2 */
  irq1State=inportByte(0x21);
  irq2State=inportByte(0xA1);

  /* Shut Off Both IRQS */
  outportByte(0x21, 0xFF);
  outportByte(0xA1, 0xFF);

  /* Save CR0 */
  asm(
    "movl %%cr0, %%ebx\n"
    : "=a"(cr0)
    :
    : "ebx"
    );

  asm("wbinvd");
  asm(
    "movl %%ebx, %%cr0\n"
    :
    : "a" (cr0 | 0x00000001 | 0x40000000 | 0x20000000)
    : "ebx"
    );

  while(memKb<4096 && memCount!=0) {
    memKb++;
    if (memCount == -1) memCount = 0;
    memCount+=1024*1024;
    mem=(unsigned long *)memCount;
    tempMemory=*mem;
    *mem=0x55AA55AA;
    asm("":::"memory");
    if (*mem!=0x55AA55AA) {
      memCount=0;
      }
    else {
      *mem=0xAA55AA55;
      asm("":::"memory");
      if (*mem!=0xAA55AA55) {
        memCount=0;
        }
      }
    asm("":::"memory");
    *mem=tempMemory;
    }
  asm(
    "movl %%ebx, %%cr0\n"
    :
    : "a" (cr0)
    : "ebx"
    );

  /* Return IRQ 1 & 2's States */
  outportByte(0x21, irq1State);
  outportByte(0xA1, irq2State);
  return((memKb*1024*1024)/4096);
  }

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

Function: void initMmap();
Description: This Function Initializes The Memory Map For the System
Notes:

************************************************************************/
void initMmap() {
  int i=0,memStart=0;
  numPages = countMemory();
  //Set Memory Map To Point To First Physical Page That We Will Use
  memoryMap = (mMap *) 0x101000;
  //Initialize Map Make All Pages Not Available
  for (i=0;i<numPages;i++) {
    memoryMap[i].cowCounter = 0x0;
    memoryMap[i].status = memNotavail;
    memoryMap[i].pid = -2;
    memoryMap[i].pageAddr = i*4096;
    }
  //Calculate Start Of Free Memory
  memStart = (0x101000/0x1000);
  memStart += (((sizeof(mMap) * numPages)+(sizeof(mMap)-1))/0x1000);
  //Initialize All Free Pages To Available
  memoryMap[(0x100000/0x1000)].status = memAvail;
  freePages++;
  for (i=memStart;i<numPages;i++) {
    memoryMap[i].status = memAvail;
    freePages++;
    }
  //Return
  return;
  }

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

Function: uLong findFreePage(pid_t pid);
Description: This Returns A Free  Physical Page Address Then Marks It
             Not Available As Well As Setting The PID To The Proccess
             Allocating This Page
Notes:

************************************************************************/  
uLong findFreePage(pid_t pid) {
  int i=0x0;
  uInt32 *buf = 0x0;
  //Lets Look For A Free Page
  if (pid < -1) { pid = -1; }
  for (i=0;i<=numPages;i++) {
    /*
    If We Found A Free Page Set It To Not Available
    After That Set Its Own And Return The Address
    */
    if ((memoryMap[i].status == memAvail) && (memoryMap[i].cowCounter == 0)) {
      memoryMap[i].status = memNotavail;
      memoryMap[i].pid = pid;
      freePages--;
      systemVitals->freePages = freePages;
      buf = (uInt32 *)memoryMap[i].pageAddr;
      /*
      for (x=0;x<0x1000;x++) {
        buf[x] = 0x0;
        }
      */
      return(memoryMap[i].pageAddr);
      }
    }
  //If No Free Memory Is Found Return NULL
  //kprintf("Out Of Memory!!!!\n");
  return(0x0);
  }

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

Function: void adjustCowCounter(uLong baseAddr,int adjustment);
Description: This Adjust The COW Counter For Page At baseAddr It Will
             Error If The Count Goes Below 0
Notes:

08/01/02 - I Think If Counter Gets To 0 I Should Free The Page

************************************************************************/
void adjustCowCounter(uLong baseAddr,int adjustment) {
  int memoryMapIndex = (baseAddr/4096);
  //Adjust COW Counter
  //kprintf("COW (%i[%i]%x)",memoryMapIndex,memoryMap[memoryMapIndex].cowCounter,baseAddr);
  memoryMap[memoryMapIndex].cowCounter += adjustment;
  //kprintf("(%i[%i]%x)\n",memoryMapIndex,memoryMap[memoryMapIndex].cowCounter,baseAddr);
  if (memoryMap[memoryMapIndex].cowCounter == 0) {
    memoryMap[memoryMapIndex].status = memAvail;
    memoryMap[memoryMapIndex].cowCounter = 0x0;
    memoryMap[memoryMapIndex].pid = -3;
    freePages++;
    systemVitals->freePages = freePages;
    }
  //Return
  return;
  }

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

Function: void freeProcessPages(pid_t pid);
Description: This Function Will Free Up Memory For The Exiting Process
Notes:

08/04/02 - Added Checking For COW Pages First
************************************************************************/
void freeProcessPages(pid_t pid) {
  int i=0,x=0;
  uLong *tmpPageTable = 0x0;
  uLong *tmpPageDir   = (uLong *)parentPageDirAddr;
  //Check Page Directory For An Avail Page Table
  for (i=0;i<=0x300;i++) {
    if (tmpPageDir[i] != 0) {
      //Set Up Page Table Pointer
      tmpPageTable = (uLong *)(tablesBaseAddress + (i * 0x1000));
      //Check The Page Table For COW Pages
      for (x=0;x<pageEntries;x++) {
        //If The Page Is COW Adjust COW Counter
        if (((uLong)tmpPageTable[x] & pageCow) == pageCow) {
          adjustCowCounter(((uLong)tmpPageTable[x] & 0xFFFFF000),-1);
          }
        }
      }
    }
  //Loop Through Pages To Find Pages Owned By Process
  for (i=0;i<numPages;i++) {
    if (memoryMap[i].pid == pid) {
      //Check To See If The cowCounter Is Zero If So We Can Ree It
      if (memoryMap[i].cowCounter == 0) {
        memoryMap[i].status = memAvail;
        memoryMap[i].cowCounter = 0x0;
        memoryMap[i].pid = -3;
        freePages++;
        systemVitals->freePages = freePages;
        }
      }
    }
  //Return
  return;    
  }  
