about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--Makefile.am3
-rw-r--r--src/tools/http_common.c28
-rw-r--r--src/tools/http_common.h2
-rw-r--r--tests/unittests/test_http_common.c (renamed from tests/unittests/test_http_download.c)2
-rw-r--r--tests/unittests/test_http_common.h (renamed from tests/unittests/test_http_download.h)0
-rw-r--r--tests/unittests/tools/stub_aesgcm_download.c10
-rw-r--r--tests/unittests/tools/stub_http_common.c16
-rw-r--r--tests/unittests/tools/stub_http_download.c5
-rw-r--r--tests/unittests/tools/stub_http_upload.c3
-rw-r--r--tests/unittests/unittests.c2
10 files changed, 23 insertions, 48 deletions
diff --git a/Makefile.am b/Makefile.am
index 9f2a99de..aeb52abd 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -126,7 +126,6 @@ unittest_sources = \
 	tests/unittests/log/stub_log.c \
 	tests/unittests/database/stub_database.c \
 	tests/unittests/config/stub_accounts.c \
-	tests/unittests/tools/stub_http_common.c \
 	tests/unittests/tools/stub_http_upload.c \
 	tests/unittests/tools/stub_http_download.c \
 	tests/unittests/tools/stub_aesgcm_download.c \
@@ -156,7 +155,7 @@ unittest_sources = \
 	tests/unittests/test_cmd_disconnect.c tests/unittests/test_cmd_disconnect.h \
 	tests/unittests/test_callbacks.c tests/unittests/test_callbacks.h \
 	tests/unittests/test_plugins_disco.c tests/unittests/test_plugins_disco.h \
-	tests/unittests/test_http_download.c tests/unittests/test_http_download.h \
+	tests/unittests/test_http_common.c tests/unittests/test_http_common.h \
 	tests/unittests/unittests.c
 
 functionaltest_sources = \
diff --git a/src/tools/http_common.c b/src/tools/http_common.c
index df6f9a64..dfd0aa87 100644
--- a/src/tools/http_common.c
+++ b/src/tools/http_common.c
@@ -64,35 +64,31 @@ http_basename_from_url(const char* url)
 }
 
 void
-http_print_transfer_update(ProfWin* window, char* url,
-                           const char* fmt, ...)
+http_print_transfer_update(ProfWin* window, char* url, const char* fmt, ...)
 {
     va_list args;
 
     va_start(args, fmt);
-    char* msg;
-    if (vasprintf(&msg, fmt, args) == -1) {
-        msg = strdup(FALLBACK_MSG);
-    }
+    GString* msg = g_string_new(FALLBACK_MSG);
+    g_string_vprintf(msg, fmt, args);
     va_end(args);
 
-    win_update_entry_message(window, url, msg);
-    free(msg);
+    win_update_entry_message(window, url, msg->str);
+
+    g_string_free(msg, TRUE);
 }
 
 void
-http_print_transfer(ProfWin* window, char* url,
-                    const char* fmt, ...)
+http_print_transfer(ProfWin* window, char* url, const char* fmt, ...)
 {
     va_list args;
 
     va_start(args, fmt);
-    char* msg;
-    if (vasprintf(&msg, fmt, args) == -1) {
-        msg = strdup(FALLBACK_MSG);
-    }
+    GString* msg = g_string_new(FALLBACK_MSG);
+    g_string_vprintf(msg, fmt, args);
     va_end(args);
 
-    win_print_http_transfer(window, msg, url);
-    free(msg);
+    win_print_http_transfer(window, msg->str, url);
+
+    g_string_free(msg, TRUE);
 }
diff --git a/src/tools/http_common.h b/src/tools/http_common.h
index 41f16200..3fbc6fcd 100644
--- a/src/tools/http_common.h
+++ b/src/tools/http_common.h
@@ -36,8 +36,6 @@
 #ifndef TOOLS_HTTP_COMMON_H
 #define TOOLS_HTTP_COMMON_H
 
-#define _GNU_SOURCE 1
-
 #include "ui/window.h"
 
 char* http_basename_from_url(const char* url);
diff --git a/tests/unittests/test_http_download.c b/tests/unittests/test_http_common.c
index 96d45d03..195f370b 100644
--- a/tests/unittests/test_http_download.c
+++ b/tests/unittests/test_http_common.c
@@ -8,7 +8,7 @@
 
 #include "config.h"
 
-#include "tools/http_download.h"
+#include "tools/http_common.c"
 
 typedef struct
 {
diff --git a/tests/unittests/test_http_download.h b/tests/unittests/test_http_common.h
index a1c62a7f..a1c62a7f 100644
--- a/tests/unittests/test_http_download.h
+++ b/tests/unittests/test_http_common.h
diff --git a/tests/unittests/tools/stub_aesgcm_download.c b/tests/unittests/tools/stub_aesgcm_download.c
index 58696e80..6f4cc0ce 100644
--- a/tests/unittests/tools/stub_aesgcm_download.c
+++ b/tests/unittests/tools/stub_aesgcm_download.c
@@ -15,9 +15,13 @@ typedef struct aesgcm_download_t
     HTTPDownload* http_dl;
 } AESGCMDownload;
 
-void* aesgcm_file_get(void* userdata);
+void*
+aesgcm_file_get(void* userdata)
+{
+    return NULL;
+};
 
-void aesgcm_download_cancel_processes(ProfWin* window);
-void aesgcm_download_add_download(AESGCMDownload* download);
+void aesgcm_download_cancel_processes(ProfWin* window){};
+void aesgcm_download_add_download(AESGCMDownload* download){};
 
 #endif
diff --git a/tests/unittests/tools/stub_http_common.c b/tests/unittests/tools/stub_http_common.c
deleted file mode 100644
index 23e0a23f..00000000
--- a/tests/unittests/tools/stub_http_common.c
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef TOOLS_HTTP_COMMON_H
-#define TOOLS_HTTP_COMMON_H
-
-typedef struct prof_win_t ProfWin;
-
-char*
-http_basename_from_url(const char* url)
-{
-    return "";
-}
-
-void http_print_transfer(ProfWin* window, char* url, const char* fmt, ...);
-void http_print_transfer_update(ProfWin* window, char* url,
-                                const char* fmt, ...);
-
-#endif
diff --git a/tests/unittests/tools/stub_http_download.c b/tests/unittests/tools/stub_http_download.c
index fb2cb1b8..5fa1c46e 100644
--- a/tests/unittests/tools/stub_http_download.c
+++ b/tests/unittests/tools/stub_http_download.c
@@ -18,9 +18,4 @@ typedef struct http_download_t
     int cancel;
 } HTTPDownload;
 
-void* http_file_get(void* userdata);
-
-void http_download_cancel_processes(ProfWin* window);
-void http_download_add_download(HTTPDownload* download);
-
 #endif
diff --git a/tests/unittests/tools/stub_http_upload.c b/tests/unittests/tools/stub_http_upload.c
index 25a81708..1b79e02d 100644
--- a/tests/unittests/tools/stub_http_upload.c
+++ b/tests/unittests/tools/stub_http_upload.c
@@ -20,8 +20,6 @@ typedef struct http_upload_t
     int cancel;
 } HTTPUpload;
 
-//GSList *upload_processes;
-
 void*
 http_file_put(void* userdata)
 {
@@ -33,6 +31,7 @@ file_mime_type(const char* const file_name)
 {
     return NULL;
 }
+
 off_t
 file_size(const char* const file_name)
 {
diff --git a/tests/unittests/unittests.c b/tests/unittests/unittests.c
index 06c1b307..cab99bf5 100644
--- a/tests/unittests/unittests.c
+++ b/tests/unittests/unittests.c
@@ -38,7 +38,7 @@
 #include "test_form.h"
 #include "test_callbacks.h"
 #include "test_plugins_disco.h"
-#include "test_http_download.h"
+#include "test_http_common.h"
 
 int
 main(int argc, char* argv[])
4' href='#n544'>544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
#include "process.h"
#include "common.h"
#include "alloc.h"
#include "vmm.h"
#include "descriptortables.h"
#include "elf.h"
#include "screen.h"
#include "debugprint.h"
#include "isr.h"
#include "timer.h"
#include "message.h"

#define MESSAGE_QUEUE_SIZE 64

Process* gKernelProcess = NULL;

Thread* gFirstThread = NULL;
Thread* gCurrentThread = NULL;

Thread* gDestroyedThread = NULL;

uint32 gProcessIdGenerator = 0;
uint32 gThreadIdGenerator = 0;

uint32 gSystemContextSwitchCount = 0;
uint32 gLastUptimeSeconds = 0;

extern Tss gTss;

uint32 generateProcessId() {
    return gProcessIdGenerator++;
}

uint32 generateThreadId() {
    return gThreadIdGenerator++;
}

uint32 getSystemContextSwitchCount() {
    return gSystemContextSwitchCount;
}

void initializeTasking() {
    Process* process = (Process*)kmalloc(sizeof(Process));
    memset((uint8*)process, 0, sizeof(Process));
    strcpy(process->name, "[kernel]");
    process->pid = generateProcessId();
    process->pd = (uint32*) KERN_PAGE_DIRECTORY;
    process->workingDirectory = getFileSystemRootNode();

    gKernelProcess = process;


    Thread* thread = (Thread*)kmalloc(sizeof(Thread));
    memset((uint8*)thread, 0, sizeof(Thread));

    thread->owner = gKernelProcess;

    thread->threadId = generateThreadId();

    thread->userMode = 0;
    thread->state = TS_RUN;
    thread->messageQueue = FifoBuffer_create(sizeof(SosoMessage) * MESSAGE_QUEUE_SIZE);
    Spinlock_Init(&(thread->messageQueueLock));
    thread->regs.cr3 = (uint32) process->pd;

    uint32 selector = 0x10;

    thread->regs.ss = selector;
    thread->regs.eflags = 0x0;
    thread->regs.cs = 0x08;
    thread->regs.eip = NULL;
    thread->regs.ds = selector;
    thread->regs.es = selector;
    thread->regs.fs = selector;
    thread->regs.gs = selector;

    thread->regs.esp = 0; //no need because this is already main kernel thread. ESP will written to this in first schedule.

    thread->kstack.ss0 = 0x10;
    thread->kstack.esp0 = 0;//For kernel threads, this is not required


    gFirstThread = thread;
    gCurrentThread = thread;
}

static int getStringArrayItemCount(char *const array[]) {
    if (NULL == array) {
        return 0;
    }

    int i = 0;
    const char* a = array[0];
    while (NULL != a) {
        a = array[++i];
    }

    return i;
}

static char** cloneStringArray(char *const array[]) {
    int itemCount = getStringArrayItemCount(array);

    char** newArray = kmalloc(sizeof(char*) * (itemCount + 1));

    for (int i = 0; i < itemCount; ++i) {
        const char* str = array[i];
        int len = strlen(str);

        char* newStr = kmalloc(len + 1);
        strcpy(newStr, str);

        newArray[i] = newStr;
    }

    newArray[itemCount] = NULL;

    return newArray;
}

static void destroyStringArray(char** array) {
    char* a = array[0];

    int i = 0;

    while (NULL != a) {
        kfree(a);

        a = array[++i];
    }

    kfree(array);
}

//This function must be called within the correct page directory for target process
static void copyArgvEnvToProcess(char *const argv[], char *const envp[]) {
    char** destination = (char**)USER_ARGV_ENV_LOC;
    int destinationIndex = 0;

    //printkf("ARGVENV: destination:%x\n", destination);

    int argvCount = getStringArrayItemCount(argv);
    int envpCount = getStringArrayItemCount(envp);

    //printkf("ARGVENV: argvCount:%d envpCount:%d\n", argvCount, envpCount);

    char* stringTable = (char*)USER_ARGV_ENV_LOC + sizeof(char*) * (argvCount + envpCount + 2);

    //printkf("ARGVENV: stringTable:%x\n", stringTable);

    for (int i = 0; i < argvCount; ++i) {
        strcpy(stringTable, argv[i]);

        destination[destinationIndex] = stringTable;

        stringTable += strlen(argv[i]) + 2;

        destinationIndex++;
    }

    destination[destinationIndex++] = NULL;

    for (int i = 0; i < envpCount; ++i) {
        strcpy(stringTable, envp[i]);

        destination[destinationIndex] = stringTable;

        stringTable += strlen(envp[i]) + 2;

        destinationIndex++;
    }

    destination[destinationIndex++] = NULL;
}

Process* createUserProcessFromElfData(const char* name, uint8* elfData, char *const argv[], char *const envp[], Process* parent, FileSystemNode* tty) {
    return createUserProcessEx(name, generateProcessId(), generateThreadId(), NULL, elfData, argv, envp, parent, tty);
}

Process* createUserProcessEx(const char* name, uint32 processId, uint32 threadId, Function0 func, uint8* elfData, char *const argv[], char *const envp[], Process* parent, FileSystemNode* tty) {
    printkf("createUserProcessEx: %s %d %d\n", name, processId, threadId);
    if (0 == processId) {
        processId = generateProcessId();
    }

    if (0 == threadId) {
        threadId = generateThreadId();
    }

    Process* process = (Process*)kmalloc(sizeof(Process));
    memset((uint8*)process, 0, sizeof(Process));
    strcpy(process->name, name);
    process->pid = processId;
    process->pd = createPd();//our page directories are identity mapped so this is also a physical address.
    process->workingDirectory = getFileSystemRootNode();

    Thread* thread = (Thread*)kmalloc(sizeof(Thread));
    memset((uint8*)thread, 0, sizeof(Thread));

    thread->owner = process;

    thread->threadId = threadId;

    thread->userMode = 1;

    thread->state = TS_RUN;

    thread->messageQueue = FifoBuffer_create(sizeof(SosoMessage) * MESSAGE_QUEUE_SIZE);
    Spinlock_Init(&(thread->messageQueueLock));

    thread->regs.cr3 = (uint32) process->pd;

    //Since stack grows backwards, we must allocate previous page. So lets substract a small amount.
    uint32 stackp = USER_STACK-4;

    if (parent) {
        process->parent = parent;

        process->workingDirectory = parent->workingDirectory;

        process->tty = parent->tty;
    }

    if (tty) {
        process->tty = tty;
    }

    char** newArgv = cloneStringArray(argv);
    char** newEnvp = cloneStringArray(envp);

    //Change memory view (page directory)
    asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"(process->pd));

    initializeProcessHeap(process);

    initializeProcessMmap(process);

    copyArgvEnvToProcess(newArgv, newEnvp);

    destroyStringArray(newArgv);
    destroyStringArray(newEnvp);

    uint32 selector = 0x23;

    thread->regs.ss = selector;
    thread->regs.eflags = 0x0;
    thread->regs.cs = 0x1B;
    thread->regs.eip = (uint32)func;
    thread->regs.ds = selector;
    thread->regs.es = selector;
    thread->regs.fs = selector;
    thread->regs.gs = selector;

    thread->regs.esp = stackp;

    char* p_addr = getPageFrame4M();
    char* v_addr = (char *) (USER_STACK - PAGESIZE_4M);
    addPageToPd(process->pd, v_addr, p_addr, PG_USER);

    thread->kstack.ss0 = 0x10;
    uint8* stack = (uint8*)kmalloc(KERN_STACK_SIZE);
    thread->kstack.esp0 = (uint32)(stack + KERN_STACK_SIZE - 4);
    thread->kstack.stackStart = (uint32)stack;

    Thread* p = gCurrentThread;

    while (p->next != NULL) {
        p = p->next;
    }

    p->next = thread;

    if (elfData) {
        printkf("about to load ELF data\n");
        uint32 startLocation = loadElf((char*)elfData);

        if (startLocation > 0) {
            thread->regs.eip = startLocation;
        }
    }

    //Restore memory view (page directory)
    asm("mov %0, %%eax ;mov %%eax, %%cr3":: "m"(gCurrentThread->regs.cr3));

    open_fs_forProcess(thread, process->tty, 0);//0: standard input
    open_fs_forProcess(thread, process->tty, 0);//1: standard output
    open_fs_forProcess(thread, process->tty, 0);//2: standard error

    printkf("running process %d\n", process->pid);
    return process;
}

//This function should be called in interrupts disabled state
void destroyThread(Thread* thread) {
    Spinlock_Lock(&(thread->messageQueueLock));

    //TODO: signal the process somehow
    Thread* previousThread = getPreviousThread(thread);
    if (NULL != previousThread) {
        previousThread->next = thread->next;

        kfree((void*)thread->kstack.stackStart);

        FifoBuffer_destroy(thread->messageQueue);

        Debug_PrintF("destroying thread %d\n", thread->threadId);

        kfree(thread);

        if (thread == gCurrentThread) {
            gCurrentThread = NULL;
        }
    }
    else {
        printkf("Could not find previous thread for thread %d\n", thread->threadId);
        PANIC("This should not be happened!\n");
    }
}

//This function should be called in interrupts disabled state
void destroyProcess(Process* process) {
    Thread* thread = gFirstThread;
    Thread* previous = NULL;
    while (thread) {
        if (process == thread->owner) {
            if (NULL != previous) {
                previous->next = thread->next;

                kfree((void*)thread->kstack.stackStart);

                Spinlock_Lock(&(thread->messageQueueLock));
                FifoBuffer_destroy(thread->messageQueue);

                Debug_PrintF("destroying thread id:%d (owner process %d)\n", thread->threadId, process->pid);

                kfree(thread);

                if (thread == gCurrentThread) {
                    gCurrentThread = NULL;
                }

                thread = previous->next;
                continue;
            }
        }

        previous = thread;
        thread = thread->next;
    }

    //Cleanup opened files
    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        if (process->fd[i] != NULL) {
            close_fs(process->fd[i]);
        }
    }

    if (process->parent) {
        thread = gFirstThread;
        while (thread) {
            if (process->parent == thread->owner) {
                if (thread->state == TS_WAITCHILD) {
                    thread->state = TS_RUN;
                }
            }

            thread = thread->next;
        }
    }

    Debug_PrintF("destroying process %d\n", process->pid);

    destroyPd(process->pd);
    kfree(process);
}

void threadStateToString(ThreadState state, uint8* buffer, uint32 bufferSize) {
    if (bufferSize < 1) {
        return;
    }

    buffer[0] = '\0';

    if (bufferSize < 10) {
        return;
    }

    switch (state) {
    case TS_RUN:
        strcpy((char*)buffer, "run");
        break;
    case TS_SLEEP:
        strcpy((char*)buffer, "sleep");
        break;
    case TS_SUSPEND:
        strcpy((char*)buffer, "suspend");
        break;
    case TS_WAITCHILD:
        strcpy((char*)buffer, "waitchild");
        break;
    case TS_WAITIO:
        strcpy((char*)buffer, "waitio");
        break;
    case TS_YIELD:
        strcpy((char*)buffer, "yield");
        break;
    default:
        break;
    }
}

void waitForSchedule() {
    //printkf("Waiting for a schedule()\n");

    enableInterrupts();
    while (TRUE) {
        halt();
    }
    disableInterrupts();
    PANIC("waitForSchedule(): Should not be reached here!!!\n");
}

void yield(uint32 count) {
    gCurrentThread->yield = count;
    gCurrentThread->state = TS_YIELD;
    enableInterrupts();
    while (gCurrentThread->yield > 0) {
        halt();
    }
    disableInterrupts();
}

int32 getEmptyFd(Process* process) {
    int32 result = -1;

    beginCriticalSection();

    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        if (process->fd[i] == NULL) {
            result = i;
            break;
        }
    }

    endCriticalSection();

    return result;
}

int32 addFileToProcess(Process* process, File* file) {
    int32 result = -1;

    beginCriticalSection();

    //printkf("addFileToProcess: pid:%d\n", process->pid);

    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        //printkf("addFileToProcess: i:%d fd[%d]:%x\n", i, i, process->fd[i]);
        if (process->fd[i] == NULL) {
            result = i;
            file->fd = i;
            process->fd[i] = file;
            break;
        }
    }

    endCriticalSection();

    return result;
}

int32 removeFileFromProcess(Process* process, File* file) {
    int32 result = -1;

    beginCriticalSection();

    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        if (process->fd[i] == file) {
            result = i;
            process->fd[i] = NULL;
            break;
        }
    }

    endCriticalSection();

    return result;
}

Thread* getThreadById(uint32 threadId) {
    Thread* p = gFirstThread;

    while (p != NULL) {
        if (p->threadId == threadId) {
            return p;
        }
        p = p->next;
    }

    return NULL;
}

Thread* getPreviousThread(Thread* thread) {
    Thread* t = gFirstThread;

    while (t->next != NULL) {
        if (t->next == thread) {
            return t;
        }
        t = t->next;
    }

    return NULL;
}

Thread* getMainKernelThread() {
    return gFirstThread;
}

Thread* getCurrentThread() {
    return gCurrentThread;
}

BOOL isThreadValid(Thread* thread) {
    Thread* p = gFirstThread;

    while (p != NULL) {
        if (p == thread) {
            return TRUE;
        }
        p = p->next;
    }

    return FALSE;
}

BOOL isProcessValid(Process* process) {
    Thread* p = gFirstThread;

    while (p != NULL) {
        if (p->owner == process) {
            return TRUE;
        }
        p = p->next;
    }

    return FALSE;
}

static void switchToTask(Thread* current);

static void updateMetrics(Thread* thread) {
    uint32 seconds = getUptimeSeconds();

    if (seconds > gLastUptimeSeconds) {
        gLastUptimeSeconds = seconds;

        Thread* t = gFirstThread;

        while (t != NULL) {
            t->contextSwitchCount = t->totalContextSwitchCount - t->totalContextSwitchCountPrevious;
            t->totalContextSwitchCountPrevious = t->totalContextSwitchCount;

            t = t->next;
        }
    }

    ++gSystemContextSwitchCount;

    ++thread->totalContextSwitchCount;
}

void schedule(TimerInt_Registers* registers) {
    Thread* current = gCurrentThread;

    if (NULL != current) {
        if (current->next == NULL && current == gFirstThread) {
            //We are the only process, no need to schedule
            return;
        }

        current->regs.eflags = registers->eflags;
        current->regs.cs = registers->cs;
        current->regs.eip = registers->eip;
        current->regs.eax = registers->eax;
        current->regs.ecx = registers->ecx;
        current->regs.edx = registers->edx;
        current->regs.ebx = registers->ebx;
        current->regs.ebp = registers->ebp;
        current->regs.esi = registers->esi;
        current->regs.edi = registers->edi;
        current->regs.ds = registers->ds;
        current->regs.es = registers->es;
        current->regs.fs = registers->fs;
        current->regs.gs = registers->gs;

        if (current->regs.cs != 0x08) {
            //Debug_PrintF("schedule() - 2.1\n");
            current->regs.esp = registers->esp_if_privilege_change;
            current->regs.ss = registers->ss_if_privilege_change;
        }
        else {
            //Debug_PrintF("schedule() - 2.2\n");
            current->regs.esp = registers->esp + 12;
            current->regs.ss = gTss.ss0;
        }

        //Save the TSS from the old process
        current->kstack.ss0 = gTss.ss0;
        current->kstack.esp0 = gTss.esp0;

        current = current->next;
        while (NULL != current) {
            if (current->state == TS_YIELD) {
                if (current->yield > 0) {
                    --current->yield;
                }

                if (current->yield == 0) {
                    current->state = TS_RUN;
                }
            }

            if (current->state == TS_SLEEP) {
                uint32 uptime = getUptimeMilliseconds();
                uint32 target = (uint32)current->state_privateData;

                if (uptime >= target) {
                    current->state = TS_RUN;
                    current->state_privateData = NULL;
                }
            }

            if (current->state == TS_RUN) {
                break;
            }
            current = current->next;
        }

        if (current == NULL) {
            //reached last process returning to first
            current = gFirstThread;
        }
    }
    else {
        //current is NULL. This means thread is destroyed, so start from the begining

        current = gFirstThread;
    }

    gCurrentThread = current;//Now gCurrentThread is the thread we are about to schedule to

    /*
    if (gCurrentThread->threadId == 5) {
        printkf("I am scheduling to %d and its EIP is %x\n", gCurrentThread->threadId, gCurrentThread->regs.eip);
    }
    */

    updateMetrics(current);
    switchToTask(current);
}

static void switchToTask(Thread* current) {
    uint32 kesp, eflags;
    uint16 kss, ss, cs;

    //Set TSS values
    gTss.ss0 = current->kstack.ss0;
    gTss.esp0 = current->kstack.esp0;

    ss = current->regs.ss;
    cs = current->regs.cs;
    eflags = (current->regs.eflags | 0x200) & 0xFFFFBFFF;

    int oldMode;
    if (cs != 0x08) {
        oldMode = USERMODE;
        kss = current->kstack.ss0;
        kesp = current->kstack.esp0;
    }
    else {
        oldMode = KERNELMODE;
        kss = current->regs.ss;
        kesp = current->regs.esp;
    }

    //switchTask is in task.asm

    asm("	mov %0, %%ss; \
        mov %1, %%esp; \
        cmpl %[KMODE], %[mode]; \
        je nextt; \
        push %2; \
        push %3; \
        nextt: \
        push %4; \
        push %5; \
        push %6; \
        push %7; \
        ljmp $0x08, $switchTask"
        :: \
        "m"(kss), \
        "m"(kesp), \
        "m"(ss), \
        "m"(current->regs.esp), \
        "m"(eflags), \
        "m"(cs), \
        "m"(current->regs.eip), \
        "m"(current), \
        [KMODE] "i"(KERNELMODE), \
        [mode] "g"(oldMode)
        );
}