diff --git a/kernel.c b/kernel.c index 79e3c58..eafef6c 100644 --- a/kernel.c +++ b/kernel.c @@ -198,7 +198,7 @@ struct process *create_process(uint32_t pc) { // Find an unused proccess control structure struct process *proc = NULL; int i; - for (i = 0; i <= PROCS_MAX; i++) { + for (i = 0; i < PROCS_MAX; i++) { if (procs[i].state == PROC_UNUSED) { proc = &procs[i]; break; @@ -262,11 +262,14 @@ void yield(void) { return; __asm__ __volatile__( + "sfence.vma\n" + "csrw satp, %[satp]\n" + "sfence.vma\n" "csrw sscratch, %[sscratch]\n" : - : [sscratch] "r" ((uint32_t) &next->stack[sizeof(next->stack)]) + : [satp] "r" (SATP_SV32 | ((uint32_t) next->page_table / PAGE_SIZE)), + [sscratch] "r" ((uint32_t) &next->stack[sizeof(next->stack)]) ); - // Context switch struct process *prev = current_proc; current_proc = next; diff --git a/kernel.h b/kernel.h index 02a6147..fe17181 100644 --- a/kernel.h +++ b/kernel.h @@ -1,6 +1,24 @@ #pragma once #include "common.h" +#define PROCS_MAX 8 // Maximum ammount of processes +#define PROC_UNUSED 0 // Unused processes control structure +#define PROC_RUNNABLE 1 // Runnable proccess +#define SATP_SV32 (1u << 31) +#define PAGE_V (1 << 0) // "Valid" bit (entry is allowed) +#define PAGE_R (1 << 1) // Readable +#define PAGE_W (1 << 2) // Writable +#define PAGE_X (1 << 3) // Executable +#define PAGE_U (1 << 4) // User (accessible in user mode) + +struct process { + int pid; // ID of a process + int state; // State of the process: either PROC_UNUSED or PROC_RUNNABLE + vaddr_t sp; // Stack pointer + uint32_t *page_table; // points to first level page table + uint8_t stack[8192]; // Kernel stack +}; + struct sbiret { long error; long value; @@ -59,24 +77,3 @@ struct trap_frame { while (1) {} \ } while (0) -#define PROCS_MAX 8 // Maximum ammount of processes - -#define PROC_UNUSED 0 // Unused processes control structure -#define PROC_RUNNABLE 1 // Runnable proccess - -// Page table -#define SATP_SV32 (1u << 32) -#define PAGE_V (1 << 0) // "Valid" bit (entry is allowed) -#define PAGE_R (1 << 1) // Readable -#define PAGE_W (1 << 2) // Writable -#define PAGE_X (1 << 3) // Executable -#define PAGE_U (1 << 4) // User (accessible in user mode) - -struct process { - int pid; // ID of a process - int state; // State of the process: either PROC_UNUSED or PROC_RUNNABLE - vaddr_t sp; // Stack pointer - uint32_t *page_table; - uint8_t stack[8192]; // Kernel stack -}; -