/*****************************************************************************************
 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 <ubixos/sched.h>
#include <ubixos/kpanic.h>
#include <ubixos/spinlock.h>
#include <ubixos/endtask.h>
#include <ubixos/vitals.h>
#include <vfs/mount.h>
#include <lib/kmalloc.h>
#include <lib/kprintf.h>
#include <vmm/vmm.h>
#include <sys/gdt.h>
#include <sys/idt.h>
#include <isa/8259.h>

extern union descriptorTableUnion ubixGDT[5];

static spinLock_t schedSpinLock = SPIN_LOCK_INITIALIZER;
static spinLock_t schedTaskSpinLock = SPIN_LOCK_INITIALIZER;

kTask_t *taskList = 0x0;
uInt32  nextID    = -1;
kTask_t *_current = 0x0;
kTask_t *_usedMath = 0x0;


prioQueue_t *prioLevels[MAXPRIOLEVELS - 1];
prioQueue_t *prioQStart = 0x0;
prioQueue_t *_currentQueue = 0x0;


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

Function: int schedInit()

Description: This function is used to enable the kernel scheduler

Notes:

02/20/2004 - Approved for quality

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


int 
schedInit() 
{        
        int i;
        kTask_t *tmpTask = (kTask_t *)kmalloc(sizeof(kTask_t));

        if (tmpTask == 0x0) {
                kpanic("Error: kmalloc failed trying to initialize the task list\n");
                return(0x1);
        }
        
        /* Set up the defaults for the initial task */
        tmpTask->prev  = 0x0;
        tmpTask->next  = 0x0;
        tmpTask->id    = nextID++;
        tmpTask->state = DEAD;
        tmpTask->nice  = MAXPRIOLEVELS/2 + 1; 
        _current       = tmpTask;

        /* Allocating memory for the priority queues */
        for (i = 0; i < MAXPRIOLEVELS; i++) {
                prioQueue_t *tmpPrioQ;

                tmpPrioQ = (prioQueue_t *)kmalloc(sizeof(prioQueue_t));
                tmpPrioQ->start = 0x0;
                tmpPrioQ->prio  = i;
                prioLevels[i] = tmpPrioQ;
                if (prioQStart == 0) tmpPrioQ->next = 0x0;
                else tmpPrioQ->next = prioQStart;
                prioQStart = tmpPrioQ;
        }

        taskList = prioLevels[tmpTask->nice]->start = tmpTask;
        _currentQueue = prioLevels[tmpTask->nice];

        /* Print out information on scheduler */
        kprintf("sched0 solar - Address: [0x%X]\n", prioQStart);
        
        /* Return so we know everything went well */
        return(0x0); 
}


void 
sched()
{
        uInt32 memAddr   = 0x0;
        kTask_t *tmpTask = 0x0;
        struct tssStruct *gpfTSS = (struct tssStruct *)0x4200;

        spinLock(&schedSpinLock);

        gpfTSS->eip            = (unsigned int)&_int13;
        gpfTSS->esp            = 0x1CFFF;
        gpfTSS->ebp            = 0x1CFFF;
        gpfTSS->eflags         = 0x206;

 schedStart:
        /* Yield the next task from the current prio queue */
        for (tmpTask = _current->next; tmpTask; tmpTask = tmpTask->next) {
                if (tmpTask->state > 0x0) {
                        _current = tmpTask;
                        break;
                }
        }

        /* Finished all the tasks from the current prio queue */
        if (0x0 == tmpTask) {
                /* Moving to the next queue which contains tasks */
                do {
                        if (0x0 == _currentQueue->next)
                                _currentQueue = prioQStart;
                        else
                                _currentQueue = _currentQueue->next;
                } while (_currentQueue->start == 0x0);
                
                _current = _currentQueue->start;
                goto schedStart;
        }
        
        /* Setting the timeslice this task is allowed to run */
        systemVitals->quantum = _current->timeSlice;
        memAddr = (uInt32)&(_current->tss);
        
        if (_current->state > 0x0) {
                if (_current->oInfo.v86Task == 0x1) {
                        //kprintf("v86Task\n");
                        irqDisable(0x0);
                }
                
                ubixGDT[4].descriptor.baseLow  = (memAddr & 0xFFFF);
                ubixGDT[4].descriptor.baseMed  = ((memAddr >> 16) & 0xFF);
                ubixGDT[4].descriptor.baseHigh = (memAddr >> 24);
                ubixGDT[4].descriptor.access   = '\x89';
                
                spinUnlock(&schedSpinLock);
                
                asm("ljmp $0x20,$0\n");
        }

        spinUnlock(&schedSpinLock);

        return;
}


kTask_t *
schedNewTask() 
{
        kTask_t *tmpTask  = (kTask_t *)kmalloc(sizeof(kTask_t));
        kTask_t *ll = 0x0;
        spinLock(&schedTaskSpinLock);
        
        /* Filling in tasks attrs */
        tmpTask->usedMath  = 0x0;
        tmpTask->id        = nextID++;
        tmpTask->state     = NEW;
        tmpTask->nice      = _current->nice;
        tmpTask->timeSlice = systemVitals->dQuantum * tmpTask->nice;
        //tmpTask->oInfo.container = findMount("s"); <- No idea what this is 
        tmpTask->oInfo.cwd      = (char *)kmalloc(1024);
       
        /* Looking for a place in the proper prio queue to place the task */
        for (ll = prioLevels[_current->nice]->start; ll; ll = ll->next) {
                if (0x0 == ll->next) {
                        tmpTask->next = 0x0;
                        ll->next = tmpTask;
                        break;
                }
        }

        /* This prio queue has no task in it */
        if (0x0 == ll) {
                tmpTask->next = 0x0;
                prioLevels[_current->nice]->start = tmpTask;
        }
        
        spinUnlock(&schedTaskSpinLock);
        return(tmpTask);
}


/*
 * This is at least O(N)... it was written to 
 * have it functional; soon it will be changed to O(1).
 */

int 
schedDeleteTask(uInt32 id) 
{
        kTask_t *tmpTask = 0x0; 
        prioQueue_t *pQ  = 0x0;

        spinLock(&schedTaskSpinLock);

        /* Checking each prio queue */
        for (pQ = prioQStart; pQ; pQ = pQ->next) {

                /* Checking each task from the prio queue */
                for (tmpTask = pQ->start; tmpTask; tmpTask = tmpTask->next) {
                        if (tmpTask->id == id) {
                                tmpTask->prev->next = tmpTask->next;

                                /* We resort back to the initial task*/
                                if (_current == tmpTask) {
                                        _current == taskList;
                                }
                        }
                }
        }

        kfree(tmpTask);
        spinUnlock(&schedTaskSpinLock);
        return(0x0);
}


kTask_t * 
schedFindTask(uInt32 id) 
{
        kTask_t *tmpTask = 0x0; 
        prioQueue_t *pQ  = 0x0;

        for (pQ = prioQStart; pQ; pQ = pQ->next) {
                for (tmpTask = pQ->start; tmpTask; tmpTask = tmpTask->next) {
                        if (tmpTask->id == id) {
                                return(tmpTask);
                        }
                }
        }

        return(0x0);
}


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

 Function: void schedEndTask()

 Description: This function will end a task

 Notes:

  02/20/2004 - Approved for quality

************************************************************************/
void 
schedEndTask(pidType pid) {
        endTask(_current->id);
        schedYield();
}

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

Function: int schedEndTask()

Description: This function will yield a task 

Notes:

02/20/2004 - Approved for quality

************************************************************************/
void 
schedYield() {
        sched();
}

/***
 $Log$
 Revision 1.10  2004/06/18 13:05:47  solar
 Changed the scheduler by adding the first rudiments of priority; vitals.c initializes the system's default quantum to 40

 Revision 1.9  2004/06/04 13:29:56  reddawg
 libc: modified mkdir(); interface
 kpanic: kPanic(); now says kPanic: %s
 system: now reboots when receives message for reboot
         also when command start sde is received by system the STD is started

 Revision 1.8  2004/05/25 16:10:46  reddawg
 Spin Locks

 Revision 1.7  2004/05/21 21:15:04  reddawg
 Fixed a few bugs which prevented the system from loadin

 Revision 1.6  2004/05/21 15:49:13  reddawg
 The os does better housekeeping now when a task is exited

 Revision 1.5  2004/05/21 12:44:17  reddawg
 Cleaned Up

 Revision 1.4  2004/05/19 04:07:43  reddawg
 kmalloc(size,pid) no more it is no kmalloc(size); the way it should of been

 Revision 1.3  2004/05/15 02:30:28  reddawg
 Lots of changes


 END
 ***/
