/*****************************************************************************************
 Copyright (c) 2002-2004 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$

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

#include <lib/kmalloc.h>
#include <lib/kprintf.h>
#include <sys/video.h>
#include <ubixos/kpanic.h>
#include <ubixos/sched.h>
#include <ubixos/spinlock.h>
#include <vmm/vmm.h>

struct memDescriptor *kernDesc      = 0x0;
struct memDescriptor *freeKernDesc  = 0x0;
struct memDescriptor *emptyKernDesc = 0x0;

static spinLock_t  mallocSpinLock = SPIN_LOCK_INITIALIZER;

void initMalloc() {
  int i=0;
  struct memDescriptor *tmpDesc1 = 0x0;
  struct memDescriptor *tmpDesc2 = 0x0;
  emptyKernDesc = (struct memDescriptor *)vmmGetFreeKernelPage(sysID,4);
  tmpDesc1 = emptyKernDesc;
  tmpDesc1->prev = 0x0;
  tmpDesc1->status = 0x0;
  tmpDesc1->limit  = 0x0;
  for (i=1;i<((4096/sizeof(struct memDescriptor))*4);i++) {
    tmpDesc2 = &emptyKernDesc[i];
    tmpDesc2->prev = tmpDesc1;
    tmpDesc1->next = tmpDesc2;
    tmpDesc2->status = 0x0;
    tmpDesc2->limit  = 0x0;
    tmpDesc1 = tmpDesc2;
    }
  tmpDesc1->next = 0x0;
  //Return
  return;
  }

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

Function: void *getEmptyDesc()
Description: Find An Empty Descriptor

Notes:

02/17/03 - Is This Efficient?

************************************************************************/    
void *getEmptyDesc() {
  struct memDescriptor *tmpDesc = emptyKernDesc;
  if (tmpDesc != 0x0) {
    emptyKernDesc       = tmpDesc->next;
    emptyKernDesc->prev = 0x0;
    tmpDesc->next       = 0x0;
    tmpDesc->prev       = 0x0;
    return(tmpDesc);
    }
  kpanic("Error Finding Empty Descriptor!\n");
  return(0x0);
  }

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

Function: void *kmalloc(uInt32 len)
Description: Allocate Kernel Memory

Notes:

02/17/03 - Do I Still Need To Pass In The Pid?

************************************************************************/    
void *kmalloc(uInt32 len) {
  struct memDescriptor *tmpDesc1 = 0x0;
  struct memDescriptor *tmpDesc2 = 0x0;
  char                 *buf      = 0x0;
  int                  i         = 0x0;

  spinLock(&mallocSpinLock);

  //If Kernel Descriptor Is NULL Initialize Malloc
  if (emptyKernDesc == 0x0) {
    initMalloc();
    }
  len = (len + 15) & 0xFFFFFFF0;
  if (len == 0x0) {
    kpanic("Malloc of Size 0 Requested\n");
    spinUnlock(&mallocSpinLock);
    return(0x0);
    }
  for (tmpDesc1 = freeKernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) {
    if (tmpDesc1->limit >= len) {
      tmpDesc1->status = 0x1;
      if (tmpDesc1->prev != 0x0) {
        tmpDesc1->prev->next = tmpDesc1->next;
        tmpDesc1->next->prev = tmpDesc1->prev;
        }
      else {
        freeKernDesc = tmpDesc1->next;
        freeKernDesc->prev = 0x0;
        }
      tmpDesc1->prev = 0x0;
      tmpDesc1->next = kernDesc;
      kernDesc->prev = tmpDesc1;
      kernDesc = tmpDesc1;
      if (tmpDesc1->limit > (len + 16)) {
        tmpDesc2 = getEmptyDesc();
        tmpDesc2->limit = tmpDesc1->limit - len;
        tmpDesc1->limit = len;
        tmpDesc2->baseAddr = tmpDesc1->baseAddr + len;
        tmpDesc2->status = 0x0;
        tmpDesc2->next = 0x0;
        tmpDesc2->prev = 0x0;
        insertFreeDesc(tmpDesc2);
        }
      buf = (char *)tmpDesc1->baseAddr;
      for (i=0;i<tmpDesc1->limit;i++) {
        (char)buf[i] = (char)0x0;
        }
      spinUnlock(&mallocSpinLock);
      return(tmpDesc1->baseAddr);
      }
    }
  tmpDesc1 = getEmptyDesc();
  if (tmpDesc1 != 0x0) {
    tmpDesc1->baseAddr = (struct memDescriptor *)vmmGetFreeKernelPage(sysID,((len + 4095)/4096));
    tmpDesc1->limit    = len;
    tmpDesc1->status   = 0x1;
    tmpDesc1->next     = kernDesc;
    tmpDesc1->prev     = 0x0;
    kernDesc             = tmpDesc1;
    kernDesc->next->prev = tmpDesc1;
    if ((len-4096) > 0) {
      tmpDesc2           = getEmptyDesc();
      tmpDesc2->status   = 0x0;
      tmpDesc2->baseAddr = tmpDesc1->baseAddr + tmpDesc1->limit;
      tmpDesc2->limit    = ((len + 4095)/4096)*4096 - tmpDesc1->limit;
      tmpDesc2->prev     = 0x0;
      tmpDesc2->next     = 0x0;
      insertFreeDesc(tmpDesc2);
      }
      buf = (char *)tmpDesc1->baseAddr;
      for (i=0;i<tmpDesc1->limit;i++) {
        (char)buf[i] = (char)0x0;
        }
    spinUnlock(&mallocSpinLock);
    return(tmpDesc1->baseAddr);
    }
  //Return Null If Unable To Malloc
  spinUnlock(&mallocSpinLock);
  return(0x0);
  }
  
/************************************************************************

Function: void kfree(void *baseAddr)
Description: This Will Find The Descriptor And Free It

Notes:

02/17/03 - I need To Make It Join Descriptors

************************************************************************/
void kfree(void *baseAddr) {
  uInt32 *data = 0x0;
  long i     = 0x0;
  struct memDescriptor *tmpDesc1 = 0x0;
  struct memDescriptor *tmpDesc2 = 0x0;

  spinLock(&mallocSpinLock);

  for (tmpDesc1=kernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) {
    if (tmpDesc1->baseAddr == baseAddr) {
      tmpDesc1->status = 0x0;
      if (tmpDesc1->prev != 0x0) {
        tmpDesc2 = tmpDesc1->prev;
        tmpDesc2->next = tmpDesc1->next;
        }
      if (tmpDesc1->next != 0x0) {
        tmpDesc2 = tmpDesc1->next;
        tmpDesc2->prev = tmpDesc1->prev;
        }
      if (kernDesc == tmpDesc1) {
        kernDesc = tmpDesc1->next;
        }
      tmpDesc1->next = 0x0;
      tmpDesc1->prev = 0x0;
      insertFreeDesc(tmpDesc1);
      data = (long *)baseAddr;
      for (i=0;i < (tmpDesc1->limit/4);i++) {
        data[i] = 0x0;
        }
      mergeMemBlocks();
      spinUnlock(&mallocSpinLock);
      return;
      }
    }
  kprintf("Error Freeing Descriptor! [0x%X]\n",baseAddr);
  spinUnlock(&mallocSpinLock);
  return;
  }

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

Function: void insertFreeDesc(struct memDescriptor *freeDesc)
Description: This Function Inserts A Free Descriptor On The List Which Is
             Kept In Size Order

Notes:

02/17/03 - This Was Inspired By TCA's Great Wisdom -
           "[20:20:59] <TCA> You should just insert it in order"

************************************************************************/
void insertFreeDesc(struct memDescriptor *freeDesc) {
  struct memDescriptor *tmpDesc;
  freeDesc->status = 0x0;
  if (freeKernDesc != 0x0) {
    for (tmpDesc=freeKernDesc;tmpDesc;tmpDesc=tmpDesc->next) {
      if ((freeDesc->limit >= tmpDesc->limit) && (!tmpDesc->next)) {
        tmpDesc->next  = freeDesc;
        freeDesc->prev = tmpDesc;
        freeDesc->next = 0x0;
        return;
        }
      else if ((freeDesc->limit >= tmpDesc->limit) && (freeDesc->limit <= tmpDesc->next->limit)) {
        freeDesc->next      = tmpDesc->next;
        freeDesc->prev      = tmpDesc;
        tmpDesc->next->prev = freeDesc;
        tmpDesc->next       = freeDesc;
        return;
        }
      }
    }
  else {
    freeDesc->prev = 0x0;
    freeDesc->next = 0x0;
    freeKernDesc = freeDesc;
    return;
    }
  //sysErr("Error With Freeing Blocks");
  return;
  }

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

Function: void mergeMemBlocks()
Description: This Function Will Merge Free Blocks And Free Pages

Notes:

03/05/03 - We Have A Problem It Seems The First Block Is Limit 0x0

************************************************************************/
void mergeMemBlocks() {
  struct memDescriptor *tmpDesc1 = 0x0;
  struct memDescriptor *tmpDesc2 = 0x0;
  uInt32               baseAddr  = 0x0;

  return;

  //Loop The Free Descriptors See If We Can Merge Them
  for (tmpDesc1=freeKernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) {
    /*
     Compare The Base Addr With The Other Descriptors If You Find The One
     That You Are Looking For Lets Merge Them
    */
    if (tmpDesc1->limit != 0x0) {
      baseAddr = (uInt32)tmpDesc1->baseAddr + (uInt32)tmpDesc1->limit;
      for (tmpDesc2=freeKernDesc;tmpDesc2;tmpDesc2=tmpDesc2->next) {
        if ((uInt32)tmpDesc2->baseAddr == baseAddr) {
          tmpDesc1->limit += tmpDesc2->limit;
          tmpDesc2->baseAddr = 0x0;
          tmpDesc2->limit    = 0x0;
          tmpDesc2->status   = 0x0;
          if (tmpDesc2->prev) {
            tmpDesc2->prev->next = tmpDesc2->next;
            }
          if (tmpDesc2->next) {
            tmpDesc2->next->prev = tmpDesc2->prev;
            }
          tmpDesc2->prev      = 0x0;
          tmpDesc2->next      = emptyKernDesc;
          emptyKernDesc->prev = tmpDesc2;
          emptyKernDesc       = tmpDesc2;
          if (tmpDesc1->prev) {
            tmpDesc1->prev->next = tmpDesc1->next;
            }
          if (tmpDesc1->next) {
            tmpDesc1->next->prev = tmpDesc1->prev;
            }
          tmpDesc1->prev = 0x0;
          tmpDesc1->next = 0x0;
          insertFreeDesc(tmpDesc1);
          tmpDesc1 = freeKernDesc;
          break;
          }
        }
      }
    }
  return;
  }

/***
 $Log$
 Revision 1.5  2004/05/25 14:01:14  reddawg
 Implimented Better Spinlocking No More Issues With KMALLOC which actually
 was causing bizzare problems

 END
 ***/

