/**************************************************************************************
 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: schedule.cc,v 1.16 2003/04/22 13:51:46 reddawg Exp $

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

#ifdef __cplusplus
extern "C" {
#endif

#include <ubixos/schedule.h>
#include <sys/io.h>
#include <sys/gdt.h>
#include <sys/idt.h>
#include <ubixos/spinlock.h>
#include <ubixos/kpanic.h>
#include <ubixos/vitals.h>
#include <ubixos/types.h>
#include <sys/tss.h>
#include <vmm/paging.h>
#include <vmm/memory.h>
#include <lib/kmalloc.h>
#include <lib/string.h>
#include <isa/8259.h>

#include <sys/video.h>

#ifdef __cplusplus
}
#endif

#include <lib/Queue.h>

#ifndef CURRENT_CPU
#define CURRENT_CPU 0
#endif

const uInt32 schedMagicNumber = 0x253B9CF9;
spinlock_t schedSpinlock;

//waitQueue_t taskQueue;
Queue<kTask_t *> * taskQueue;
Queue<kTask_t *> * readyQueue;
Queue<kTask_t *> * exitQueue;
Queue<kTask_t *> * sleepQueue;

int numTasks = 0;
int currentProc = -1;
int lastPid = -1;
kTask_t *taskList = (kTask_t *)0xE0800000;
kTask_t *_current = 0x0,*_usedMath = 0x0;

char *tmp = 0x0;

extern union descriptorTableunion GDT[7];
extern int testVal;
      
int switches = 0;

void initScheduler(void) {
  kTask_t * firstTask = 0x0;
  
  //kprintf("Initializing Scheduler.........     ");    
  spinlockInit(&schedSpinlock);
  //waitQueueInit(&taskQueue, 0);
  taskQueue = new Queue<kTask_t *>();
  readyQueue = new Queue<kTask_t *>();
  sleepQueue = new Queue<kTask_t *>();
  exitQueue = new Queue<kTask_t *>();
  
    // create -1 task.
  firstTask = (kTask_t *) kmalloc(sizeof(kTask_t),-2);
  if (firstTask == NULL)
    kPanic("Scheduler Init: Couldn't allocate first task");
  firstTask->id = -1;
  firstTask->status = RUNNING;
  taskQueue->insert(firstTask->id, firstTask);
  currentProc = -1;
  _current = firstTask;
  numTasks = 0;
   
}
    
kTask_t * findTask() {
  kTask_t * newTask = 0x0;
  lastPid++;    
  newTask = (kTask_t *) kmalloc(sizeof(kTask_t),-2);
  if (newTask == NULL)
    kPanic("Scheduler: Couldn't allocate memory for new task");
    
  spinlockLock(&schedSpinlock, CURRENT_CPU, SPIN_SCHED);
     
  kmemset(newTask, '\0', sizeof(kTask_t));

  newTask->id = (uInt32) lastPid;
  newTask->status = STARTING;
  newTask->usedMath=0;
  newTask->cpuTime = 0;
  newTask->lastExecutedTime = 0;
  newTask->uid = -1;
  newTask->gid = -1;
  newTask->oInfo.timer     = 0x0;
  newTask->oInfo.v86Task   = 0x1;
  newTask->oInfo.curDir    = 0x0;
  newTask->oInfo.container = findMount("home");
    
  numTasks++;
  taskQueue->insert(newTask->id, newTask);
  spinlockUnlock(&schedSpinlock, CURRENT_CPU);
  return newTask;
  }
    
kTask_t * getTask(int taskId) {
  // need to optimize this function a bit.
  kTask_t * temp = 0x0;
  spinlockLock(&schedSpinlock, CURRENT_CPU, SPIN_SCHED);
  temp = taskQueue->find(taskId);
  if (NULL == temp)
    temp = exitQueue->find(taskId);
  spinlockUnlock(&schedSpinlock, CURRENT_CPU);
  return(temp);
  }

void setTaskStatus(int taskId, uInt16 status)
{
    kTask_t * temp = getTask(taskId);

    if (NULL == temp)
	return;

    setTaskStatus_task(temp, status);
    
    return;
}

void setTaskStatus_task(kTask_t * task, uInt16 status)
{
    if (NULL == task)
	return;
    spinlockLock(&schedSpinlock, CURRENT_CPU, SPIN_SCHED);
    
    //kprintf("Set status on task %d from %d to %d\n", 
    //	      task->id, task->status, status);
     
    // remove task from previous queue.
    switch(task->status)
    {
	  case SLEEP:
	      sleepQueue->remove(task->id);
	      break;

	  case READY:
	      readyQueue->remove(task->id);
	      break;

	  case EXITING:
	      taskQueue->insert(task->id, task);
	      exitQueue->remove(task->id);
	      break;

	  default:
	      break;
    }
    
    // set status
    task->status = status;
    
    // insert into new queue.
    switch(status)
    {
	  case SLEEP:
	      sleepQueue->insert(task->id, task);
	      break;

	  case READY:
	      readyQueue->insert(task->id, task);
	      break;

	  case EXITING:
	      taskQueue->remove(task->id);
	      exitQueue->insert(task->id, task);
	      //kprintf("Exiting[%d].\n", exitQueue->size());
	      break;

	  default:
	      break;
    }
    
    spinlockUnlock(&schedSpinlock, CURRENT_CPU);
    return;
}
    

volatile int schedReentrLock = -1;

void schedule() {
  
  volatile unsigned char jumpSet = 0;
  
  kTask_t * temp;
  uInt32 memAddr;
  struct tssStruct *gpfTSS = (struct tssStruct *)0x4200;
  struct tssStruct *doubleFaultTSS = (struct tssStruct *)0x4000;

  gpfTSS->eip            = (unsigned int)&_int13;
  gpfTSS->esp            = 0x1CFFF;
  gpfTSS->ebp            = 0x1CFFF;
  gpfTSS->eflags         = 0x206;
  doubleFaultTSS->eip    = (unsigned int)&doubleFault;
  doubleFaultTSS->esp    = 0x1BFFF;
  doubleFaultTSS->ebp    = 0x1BFFF;
  doubleFaultTSS->eflags = 0x206;
  
  if (numTasks == 0) {
    return;
    }
  
  /* re-entrient lock. */
  asm volatile("mov %1, %%eax; lock incl (%%eax); setz %0" 
		  : "=g" (jumpSet) 
		  : "m" (&schedReentrLock) 
		  : "eax");
  if (!jumpSet)
  {
    goto sched_done;
  }
  /* end re-entrient lock. */

  if (systemVitals->sysTicks < _current->lastExecutedTime)
    _current->cpuTime += systemVitals->sysTicks + (0xFFFFFFFF - _current->lastExecutedTime);
  else
    _current->cpuTime += systemVitals->sysTicks - _current->lastExecutedTime;      
  spinlockLock(&schedSpinlock, CURRENT_CPU, SPIN_RETURN);

  while(exitQueue->size() > 8)
    kfree(exitQueue->remove());

  if (0 == readyQueue->size())
    temp = getTask(-1);
  else
    temp = readyQueue->top();

  if (NULL == temp) {
    temp = _current;
    }

  if (NULL == temp) {
    kPanic("Scheduler: Ouch.\n");
    }
  else {
    if (RUNNING == _current->status)
      setTaskStatus_task(_current, READY);
    setTaskStatus_task(temp, RUNNING);
    temp->lastExecutedTime = systemVitals->sysTicks;
    memAddr = (uInt32) &(temp->tss);

    GDT[5].descriptor.access = '\x89';//0xE9;//
    GDT[5].descriptor.baseLow = (memAddr & 0xFFFF);
    GDT[5].descriptor.baseMed = ((memAddr >> 16) & 0xFF);
    GDT[5].descriptor.baseHigh = (memAddr >> 24);
    _current = temp;
    spinlockUnlock(&schedSpinlock, CURRENT_CPU);
    schedReentrLock = -1;
    if (_current->oInfo.timer == 0x1) {
      kprintf("Not Good");
      disableIrq(0);
      }
    
    asm("ljmp $0x28,$0\n");
    return;
  }
  
  /* 
  chooseTask = (currentProc + 1) % numTasks;
  while ((getTask(chooseTask)->status != READY) && (getTask(chooseTask)->status != RUNNING) && (loopCount < 4)) {
    if (getTask(chooseTask)->status == SLEEP) {
      if (((systemVitals->sysUptime >= getTask(chooseTask)->sleepTimeSec) && (systemVitals->sysTicks >= getTask(chooseTask)->sleepTimeMs)) || (systemVitals->sysUptime == getTask(chooseTask)->sleepTimeSec)) {
        setTaskStatus(chooseTask, READY);
        chooseTask--;
        }
      }
    chooseTask++;
    chooseTask %= numTasks;
    if (chooseTask == 0)
      loopCount++; 
    }
  if ((loopCount == 4) || (getTask(chooseTask)->status == EXITING))
    chooseTask = -1;
  if (chooseTask != -1) {
    if (getTask(chooseTask)->status == RUNNING) {
      setTaskStatus(chooseTask, READY);
      }
    currentProc = chooseTask;
    getTask(chooseTask)->lastExecutedTime = systemVitals->sysTicks;
    setTaskStatus(chooseTask, RUNNING);
    memAddr = (uInt32) &(getTask(chooseTask)->tss);
    GDT[5].descriptor.access = '\x89';//0xE9;//
    GDT[5].descriptor.baseLow = (memAddr & 0xFFFF);
    GDT[5].descriptor.baseMed = ((memAddr >> 16) & 0xFF);
    GDT[5].descriptor.baseHigh = (memAddr >> 24);
    spinlockUnlock(&schedSpinlock, CURRENT_CPU);
    schedReentrLock = -1;
    _current = getTask(chooseTask);      
    asm("ljmp $0x28,$0\n");
    }
  */
  
  spinlockUnlock(&schedSpinlock, CURRENT_CPU);
  schedReentrLock = -1;
  return;

  sched_done:
    return;
  }

void sched_yield()
{
  //kprintf("sched_yield");
  schedule();
}

void sleep(uInt32 sec, uInt32 mSec)
{
    sec += mSec / 1000;
    mSec %= 1000;

    _current->sleepTimeSec = systemVitals->sysUptime + sec + ((mSec + (systemVitals->sysTicks % 1000)) / 1000);
    _current->sleepTimeMs = mSec + systemVitals->sysTicks;

    setTaskStatus_task(_current, SLEEP);

    while(SLEEP == _current->status)
	schedule();

    return;
}

/*
waitQueue_t * waitQueueCreate(int type) {
  waitQueue_t * queue = (waitQueue_t *) kmalloc(sizeof(waitQueue_t),-2);
  if (queue == NULL)
    return NULL;
  kmemset(queue, '\0', sizeof(waitQueue_t));
  queue->magic_number = schedMagicNumber;
  queue->type = type;
  return queue;
  }

void waitQueueInit(waitQueue_t * queue, int type) {
  kmemset(queue, '\0', sizeof(*queue));
  queue->magic_number = schedMagicNumber;
  queue->type = type;
  queue->first = queue->last = NULL;
  return;
  }

void waitQueueDelete(waitQueue_t * queue) {
  struct waitQueueNode * temp;
  if (queue == NULL)
    return;
  if (queue->magic_number != schedMagicNumber)
    return;
  while (queue->first != NULL) {
    temp = queue->first;
    queue->first = queue->first->next;
    kfree(temp);
    }
  kmemset(queue, '\0', sizeof(waitQueue_t));
  kfree(queue);
  }

void waitQueueUnInit(waitQueue_t * queue) {
  struct waitQueueNode * temp;
  if (queue->magic_number != schedMagicNumber)
    return;
  while (queue->first != NULL) {
    temp = queue->first;
    queue->first = queue->first->next;
    kfree(temp);
    }
  kmemset(queue, '\0', sizeof(waitQueue_t));
  return;
  }

void waitQueueInsert(waitQueue_t * queue, void * data, int id) {
  struct waitQueueNode * temp = 0x0;
  if (queue == NULL)
    return;
  if (queue->magic_number != schedMagicNumber)
    return;
  temp = (struct waitQueueNode *) kmalloc(sizeof(struct waitQueueNode),-2);
  kmemset(temp, '\0', sizeof(struct waitQueueNode));
  temp->prev = temp->next = NULL;
  if (queue->first == NULL) {;
    queue->first = queue->last = temp;
    }
  else {
    queue->last->next = temp;
    temp->prev = queue->last;
    queue->last = temp;
    }
  temp->data = data;
  temp->id = id;
  return;
  }

void * waitQueueRemove(waitQueue_t * queue, int * id) {
  void * temp;
  if (queue == NULL)
    return NULL;
  if (queue->magic_number != schedMagicNumber)
    return NULL;
  if (queue->first == NULL)
    return NULL;
  temp = queue->first->data;
  *id = queue->first->id;
  if (queue->first->next == NULL) {
    kfree(queue->first);
    queue->first = queue->last = NULL;
    }
  else {
    queue->first = queue->first->next;
    kfree(queue->first->prev);
    queue->first->prev = NULL;
    }
  return temp;
  }

void * waitQueueFind(waitQueue_t * queue, int id) {
  struct waitQueueNode * temp = 0x0;
  if (queue == NULL)
    return NULL;
  if (queue->magic_number != schedMagicNumber)
    return NULL;
  if (queue->first == NULL)
    return NULL;
  temp = queue->first;
  while ((temp->id != id) && (temp->next != NULL)) {
    temp = temp->next;
    }
  if (temp->id == id) {
    return(temp->data);
    }
  return(NULL);
  }

*/
