Newer
Older
tree-os / src / kernel / task / task.c
#include <_stdio.h>
#include <alloc.h>
#include <list.h>
#include <task.h>

#define STACK_SIZE 0x100000

Task *currentTask;
ListElement *scheduledTasks = NULL;
ListElement *allTasks = NULL;

void createTask(Task *task, uint32_t mainFunction, uint32_t flags,
                uint32_t *pagedir) {
    listAddSet(&allTasks, task);
    void *stack = mallocTask(STACK_SIZE, task);
    task->registers.eax = 0;
    task->registers.ebx = 0;
    task->registers.ecx = 0;
    task->registers.edx = 0;
    task->registers.esi = 0;
    task->registers.edi = 0;
    task->registers.eflags = flags;
    task->registers.eip = mainFunction;
    task->registers.cr3 = (uint32_t)pagedir;
    task->registers.esp = STACK_SIZE + (uint32_t)stack;
    task->stack = stack;
    task->messages = NULL;
    task->ticksLeft = -1;
    task->timerTicks = -1;
}

void yield() {
    Task *last = currentTask;
    currentTask = popBeginning(&scheduledTasks);
    if (currentTask == NULL) {
        while (1)
            ;
        return;
    }
    switchTask(&(last->registers), &(currentTask->registers));
}

inline void yields() {
    schedule(currentTask);
    yield();
}

inline void destroyCurrentTask() {
    freeTaskAllocations(currentTask);
    yield();
}

inline Task *getCurrentTask() { return currentTask; }

inline void schedule(Task *task) { listAddSet(&scheduledTasks, task); }

inline void setRunningTask(Task *task) {
    currentTask = task;
    listAddSet(&allTasks, task);
}

inline bool isTaskQueueEmpty() { return scheduledTasks == NULL; }
inline ListElement *getAllTasks() { return allTasks; }