Switch ok with debug mode apps, implement sys_exit correctly later.

This commit is contained in:
Yifan Wu 2020-11-29 01:31:36 +08:00
parent 4e8059e222
commit 3f3e6b2b99
16 changed files with 244 additions and 147 deletions

16
os/src/task/context.rs Normal file
View file

@ -0,0 +1,16 @@
#[repr(C)]
pub struct TaskContext {
ra: usize,
s: [usize; 12],
}
impl TaskContext {
pub fn goto_restore() -> Self {
extern "C" { fn __restore(); }
Self {
ra: __restore as usize,
s: [0; 12],
}
}
}

61
os/src/task/mod.rs Normal file
View file

@ -0,0 +1,61 @@
mod context;
mod switch;
use crate::config::MAX_APP_NUM;
use crate::loader::{get_num_app, init_app_cx};
use core::cell::RefCell;
use lazy_static::*;
use switch::__switch;
pub use context::TaskContext;
struct TaskControlBlock {
task_cx_ptr: usize,
}
pub struct TaskManager {
num_app: usize,
tasks: [TaskControlBlock; MAX_APP_NUM],
current_task: RefCell<usize>,
}
unsafe impl Sync for TaskManager {}
lazy_static! {
pub static ref TASK_MANAGER: TaskManager = {
let num_app = get_num_app();
let mut tasks = [TaskControlBlock { task_cx_ptr: 0 }; MAX_APP_NUM];
for i in 0..num_app {
tasks[i] = TaskControlBlock { task_cx_ptr: init_app_cx(i) as *const _ as usize, };
}
TaskManager {
num_app,
tasks,
current_task: RefCell::new(0),
}
};
}
impl TaskManager {
pub fn run_first_task(&self) {
unsafe {
__switch(&0usize, &self.tasks[0].task_cx_ptr);
}
}
pub fn switch_to_next_task(&self) {
let current = *self.current_task.borrow();
let next = if current == self.num_app - 1 { 0 } else { current + 1 };
*self.current_task.borrow_mut() = next;
unsafe {
__switch(&self.tasks[current].task_cx_ptr, &self.tasks[next].task_cx_ptr);
}
}
}
pub fn run_first_task() {
TASK_MANAGER.run_first_task();
}
pub fn switch_to_next_task() {
TASK_MANAGER.switch_to_next_task();
}

34
os/src/task/switch.S Normal file
View file

@ -0,0 +1,34 @@
.altmacro
.macro SAVE_SN n
sd s\n, (\n+1)*8(sp)
.endm
.macro LOAD_SN n
ld s\n, (\n+1)*8(sp)
.endm
.section .text
.globl __switch
__switch:
# __switch(current_task_cx: &*const TaskContext, next_task_cx: &*const TaskContext)
# push TaskContext to current sp and save its address to where a0 points to
addi sp, sp, -13*8
sd sp, 0(a0)
# fill TaskContext with ra & s0-s11
sd ra, 0(sp)
.set n, 0
.rept 12
SAVE_SN %n
.set n, n + 1
.endr
# ready for loading TaskContext a1 points to
ld sp, 0(a1)
# load registers in the TaskContext
ld ra, 0(sp)
.set n, 0
.rept 12
LOAD_SN %n
.set n, n + 1
.endr
# pop TaskContext
addi sp, sp, 13*8
ret

7
os/src/task/switch.rs Normal file
View file

@ -0,0 +1,7 @@
use super::TaskContext;
global_asm!(include_str!("switch.S"));
extern "C" {
pub fn __switch(current_task_cx: &usize, next_task_cx: &usize);
}