/**************************************************************************************
 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.c,v 1.16 2002/11/03 20:55:02 apwillia Exp $

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

#include <ubixos/schedule.h>
#include <ubixos/io.h>
#include <ubixos/gdt.h>
#include <ubixos/idt.h>
#include <ubixos/spinlock.h>
#include <ubixos/kpanic.h>
#include <ubixos/vitals.h>
#include <ubixos/tss.h>
#include <lib/kmalloc.h>
#include <lib/kstdio.h>
#include <vmm/paging.h>
#include <vmm/memory.h>
#include <drivers/8259.h>

#ifndef CURRENT_CPU
#define CURRENT_CPU 0
#endif

const uInt32 schedMagicNumber = 0x253B9CF9;
spinlock_t schedSpinlock;

waitQueue_t taskQueue;

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 kmemset(void * dest, char value, int size) {
  size--;
  while(size >= 0)
    ((char *)dest)[size--] = value;
  }

void kmemcpy(void * dest, void * src, int size) {
    char * d = dest;
    char * s = src;
    
    size--;
     
    while(size >= 0)
    {
	d[size] = s[size];
	size--;
    }
}
	

void kstrncpy(char * dest, char * src, int size)
{
    if (size == 0)
	return;
    do
    {
	*dest = *src;
	dest++; src++;
	size--;
    }
    while(('\0' != *(src-1)) && (size));
}

void initScheduler(void) {
  kTask_t * firstTask = 0x0;
  kprintf("Initializing Scheduler.........     ");    
  spinlockInit(&schedSpinlock);
  waitQueueInit(&taskQueue, 0);
     
    // create -1 task.
    
  firstTask = kmalloc(sizeof(kTask_t),-1);
  //kprintf("from malloc %08x\n", firstTask);
  if (firstTask == NULL)
    kPanic("Scheduler Init: Couldn't allocate first task");
  firstTask->id = -1;
  firstTask->status = EMPTY;
  waitQueueInsert(&taskQueue, firstTask, firstTask->id);
  currentProc = -1;
  _current = firstTask;
  numTasks = 0;
  //kprintf("<<Init\n");
  //setVector(timerInt, mVec, (dInt + dPresent + dDpl3));
  kprintf("INITIALIZED\n");
  }
    
kTask_t * findTask() {
  kTask_t * newTask = 0x0;
  //kprintf(">>FindTask\n");
  lastPid++;    
  newTask = kmalloc(sizeof(kTask_t),lastPid);
  //kprintf("from malloc %08x\n", newTask); 
  if (newTask == NULL)
    kPanic("Scheduler: Couldn't allocate memory for new task");
    
  spinlockLock(&schedSpinlock, CURRENT_CPU);
     
  kmemset(newTask, '\0', sizeof(kTask_t));

  newTask->id = lastPid;
  newTask->status = EMPTY;
  newTask->usedMath=0;
  newTask->cpuTime = 0;
  newTask->lastExecutedTime = 0;
  newTask->uid = -1;
  newTask->gid = -1;
    
  numTasks++;
  waitQueueInsert(&taskQueue, newTask, newTask->id);
  spinlockUnlock(&schedSpinlock, CURRENT_CPU);
  return newTask;
  }
    
kTask_t * getTask(int taskId) {
  kTask_t * temp;
  spinlockLock(&schedSpinlock, CURRENT_CPU);
  temp = waitQueueFind(&taskQueue, 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;

    task->status = status;

    return;
}
    

volatile int schedReentrLock = 0;

void schedule() {
  int chooseTask;
  uInt32 memAddr;
  int loopCount = 0;
  if (numTasks == 0) {
    return;
    }
  if (systemVitals->sysTicks < _current->lastExecutedTime)
    _current->cpuTime += systemVitals->sysTicks + (0xFFFFFFFF - _current->lastExecutedTime);
  else
    _current->cpuTime += systemVitals->sysTicks - _current->lastExecutedTime;    
  if (schedReentrLock != 0)
      return;
  schedReentrLock = 1;
  spinlockLock(&schedSpinlock, CURRENT_CPU);
  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)
    chooseTask = -1;
  if (chooseTask != -1) {
    if (getTask(chooseTask)->status == RUNNING) {
      setTaskStatus(chooseTask, READY);
      }
    currentProc = chooseTask;
    _current = getTask(chooseTask);
    getTask(chooseTask)->lastExecutedTime = systemVitals->sysTicks;
    setTaskStatus(chooseTask, RUNNING);
    memAddr = (uInt32) &(getTask(chooseTask)->tss);
    GDT[4].descriptor.access = 0x89;//0xE9;//
    GDT[4].descriptor.baseLow = (memAddr & 0xFFFF);
    GDT[4].descriptor.baseMed = ((memAddr >> 16) & 0xFF);
    GDT[4].descriptor.baseHigh = (memAddr >> 24);
    spinlockUnlock(&schedSpinlock, CURRENT_CPU);
    schedReentrLock = 0;
    asm("ljmp $0x20,$0\n");
    }
  spinlockUnlock(&schedSpinlock, CURRENT_CPU);
  schedReentrLock = 0;
  }

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),-1);
  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),-1);
  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);
  }
