task.rs 11.5 KB
Newer Older
hm12299's avatar
hm12299 已提交
1 2 3 4 5 6 7
use crate::mm::{
    MemorySet,
    PhysPageNum,
    KERNEL_SPACE, 
    VirtAddr,
    translated_refmut,
};
hm12299's avatar
hm12299 已提交
8
//use crate::timer::get_time_ms;
hm12299's avatar
hm12299 已提交
9 10 11 12 13 14 15
use crate::trap::{TrapContext, trap_handler};
use crate::config::{TRAP_CONTEXT};
use super::TaskContext;
use super::{PidHandle, pid_alloc, KernelStack};
use alloc::sync::{Weak, Arc};
use alloc::vec;
use alloc::vec::Vec;
hm12299's avatar
hm12299 已提交
16
use alloc::string::{String, ToString};
hm12299's avatar
hm12299 已提交
17 18
use spin::{Mutex, MutexGuard};
use crate::fs::{File, ProcInfo, Stdin, Stdout};
hm12299's avatar
hm12299 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#[derive(Copy, Clone)]
pub struct SyscallCount{
    pub syscall_dup: (usize, usize),
    pub syscall_open: (usize, usize),
    pub syscall_close: (usize, usize),
    pub syscall_pipe: (usize, usize),
    pub syscall_read: (usize, usize),
    pub syscall_write: (usize, usize),
    pub syscall_exit: (usize, usize),
    pub syscall_yield: (usize, usize),
    pub syscall_get_time: (usize, usize),
    pub syscall_getpid: (usize, usize),
    pub syscall_fork: (usize, usize),
    pub syscall_exec: (usize, usize),
    pub syscall_waitpid: (usize, usize),
}
hm12299's avatar
hm12299 已提交
35 36 37 38 39 40 41

pub struct TaskControlBlock {
    // immutable
    pub pid: PidHandle,
    pub kernel_stack: KernelStack,
    // mutable
    inner: Mutex<TaskControlBlockInner>,
hm12299's avatar
hm12299 已提交
42
    pub ppid: isize,
hm12299's avatar
hm12299 已提交
43 44 45 46 47 48 49
}

pub struct TaskControlBlockInner {
    pub trap_cx_ppn: PhysPageNum,
    pub base_size: usize,
    pub task_cx_ptr: usize,
    pub task_status: TaskStatus,
hm12299's avatar
hm12299 已提交
50
    pub name: String,
hm12299's avatar
hm12299 已提交
51 52 53 54 55
    pub memory_set: MemorySet,
    pub parent: Option<Weak<TaskControlBlock>>,
    pub children: Vec<Arc<TaskControlBlock>>,
    pub exit_code: i32,
    pub fd_table: Vec<Option<Arc<dyn File + Send + Sync>>>,
hm12299's avatar
hm12299 已提交
56
    pub start_time: usize,
C
chenzhiy2001 已提交
57
    pub cpu_time: usize,
hm12299's avatar
hm12299 已提交
58
    pub syscall: Arc<Mutex<SyscallCount>>,
hm12299's avatar
hm12299 已提交
59 60 61 62 63 64 65 66 67 68 69 70
}

impl TaskControlBlockInner {
    pub fn get_task_cx_ptr2(&self) -> *const usize {
        &self.task_cx_ptr as *const usize
    }
    pub fn get_trap_cx(&self) -> &'static mut TrapContext {
        self.trap_cx_ppn.get_mut()
    }
    pub fn get_user_token(&self) -> usize {
        self.memory_set.token()
    }
hm12299's avatar
hm12299 已提交
71
    pub fn get_status(&self) -> TaskStatus {
hm12299's avatar
hm12299 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85
        self.task_status
    }
    pub fn is_zombie(&self) -> bool {
        self.get_status() == TaskStatus::Zombie
    }
    pub fn alloc_fd(&mut self) -> usize {
        if let Some(fd) = (0..self.fd_table.len())
            .find(|fd| self.fd_table[*fd].is_none()) {
            fd
        } else {
            self.fd_table.push(None);
            self.fd_table.len() - 1
        }
    }
hm12299's avatar
hm12299 已提交
86
    /*pub fn stamp(&mut self){
C
chenzhiy2001 已提交
87 88 89 90
        self.start_run_stamp = get_time_ms();
    }
    pub fn cpu_time_update(&mut self){
        self.cpu_time += get_time_ms()-self.start_run_stamp;
hm12299's avatar
hm12299 已提交
91
    }*/
hm12299's avatar
hm12299 已提交
92 93 94 95 96 97
}

impl TaskControlBlock {
    pub fn get_info(&self)-> ProcInfo{
        let pid = self.getpid();
        let status = self.inner.lock().get_status();
hm12299's avatar
hm12299 已提交
98
        let name = self.get_name();
hm12299's avatar
hm12299 已提交
99 100 101
        let ppid = self.get_ppid();
        let cpu_time = self.get_cpu_time();
        let syscall_cnt = self.get_syscall_cnt();
hm12299's avatar
hm12299 已提交
102 103
        ProcInfo{
            pid,
hm12299's avatar
hm12299 已提交
104
            name,
hm12299's avatar
hm12299 已提交
105
            status,
hm12299's avatar
hm12299 已提交
106 107 108
            ppid,
            cpu_time,
            syscall_cnt,
hm12299's avatar
hm12299 已提交
109 110 111 112 113 114
        }
    }

    pub fn acquire_inner_lock(&self) -> MutexGuard<TaskControlBlockInner> {
        self.inner.lock()
    }
hm12299's avatar
hm12299 已提交
115 116 117 118 119

    pub fn set_name(&self, name: String){
        self.acquire_inner_lock().name = name;
    }

hm12299's avatar
hm12299 已提交
120 121 122 123 124 125 126 127 128 129 130
    pub fn new(elf_data: &[u8]) -> Self {
        // memory_set with elf program headers/trampoline/trap context/user stack
        let (memory_set, user_sp, entry_point) = MemorySet::from_elf(elf_data);
        let trap_cx_ppn = memory_set
            .translate(VirtAddr::from(TRAP_CONTEXT).into())
            .unwrap()
            .ppn();
        // alloc a pid and a kernel stack in kernel space
        let pid_handle = pid_alloc();
        let kernel_stack = KernelStack::new(&pid_handle);
        let kernel_stack_top = kernel_stack.get_top();
hm12299's avatar
hm12299 已提交
131
        let name = String::new();
hm12299's avatar
hm12299 已提交
132 133 134 135 136
        // push a task context which goes to trap_return to the top of kernel stack
        let task_cx_ptr = kernel_stack.push_on_top(TaskContext::goto_trap_return());
        let task_control_block = Self {
            pid: pid_handle,
            kernel_stack,
hm12299's avatar
hm12299 已提交
137
            ppid: -1,
hm12299's avatar
hm12299 已提交
138 139 140 141 142
            inner: Mutex::new(TaskControlBlockInner {
                trap_cx_ppn,
                base_size: user_sp,
                task_cx_ptr: task_cx_ptr as usize,
                task_status: TaskStatus::Ready,
hm12299's avatar
hm12299 已提交
143
                name,
hm12299's avatar
hm12299 已提交
144 145 146 147 148 149 150 151 152 153 154
                memory_set,
                parent: None,
                children: Vec::new(),
                exit_code: 0,
                fd_table: vec![
                    // 0 -> stdin
                    Some(Arc::new(Stdin)),
                    // 1 -> stdout
                    Some(Arc::new(Stdout)),
                    // 2 -> stderr
                    Some(Arc::new(Stdout)),
155 156 157
                    // ? -> proc_info
                    // 注意调用号严格来说不是自己分配的,打开一个新文件默认分配能分配的最小调用号
                    // Some(Arc::new(ProcInfoList)),
hm12299's avatar
hm12299 已提交
158
                ],
hm12299's avatar
hm12299 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
                start_time: 0,
                cpu_time: 0,
                syscall: Arc::new(Mutex::new(SyscallCount{
                    syscall_dup: (0, 0),
                    syscall_open: (0, 0),
                    syscall_close: (0, 0),
                    syscall_pipe: (0, 0),
                    syscall_read: (0, 0),
                    syscall_write: (0, 0),
                    syscall_exit: (0, 0),
                    syscall_yield: (0, 0),
                    syscall_get_time: (0, 0),
                    syscall_getpid: (0, 0),
                    syscall_fork: (0, 0),
                    syscall_exec: (0, 0),
                    syscall_waitpid: (0, 0),
                }))
                //start_run_stamp:0,
hm12299's avatar
hm12299 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
            }),
        };
        // prepare TrapContext in user space
        let trap_cx = task_control_block.acquire_inner_lock().get_trap_cx();
        *trap_cx = TrapContext::app_init_context(
            entry_point,
            user_sp,
            KERNEL_SPACE.lock().token(),
            kernel_stack_top,
            trap_handler as usize,
        );
        task_control_block
    }
    pub fn exec(&self, elf_data: &[u8], args: Vec<String>) {
        // memory_set with elf program headers/trampoline/trap context/user stack
        let (memory_set, mut user_sp, entry_point) = MemorySet::from_elf(elf_data);
        let trap_cx_ppn = memory_set
            .translate(VirtAddr::from(TRAP_CONTEXT).into())
            .unwrap()
            .ppn();
        // push arguments on user stack
        user_sp -= (args.len() + 1) * core::mem::size_of::<usize>();
        let argv_base = user_sp;
        let mut argv: Vec<_> = (0..=args.len())
            .map(|arg| {
                translated_refmut(
                    memory_set.token(),
                    (argv_base + arg * core::mem::size_of::<usize>()) as *mut usize
                )
            })
            .collect();
        *argv[args.len()] = 0;
        for i in 0..args.len() {
            user_sp -= args[i].len() + 1;
            *argv[i] = user_sp;
            let mut p = user_sp;
            for c in args[i].as_bytes() {
                *translated_refmut(memory_set.token(), p as *mut u8) = *c;
                p += 1;
            }
            *translated_refmut(memory_set.token(), p as *mut u8) = 0;
        }
        // make the user_sp aligned to 8B for k210 platform
        user_sp -= user_sp % core::mem::size_of::<usize>();

        // **** hold current PCB lock
        let mut inner = self.acquire_inner_lock();
        // substitute memory_set
        inner.memory_set = memory_set;
        // update trap_cx ppn
        inner.trap_cx_ppn = trap_cx_ppn;
        // initialize trap_cx
        let mut trap_cx = TrapContext::app_init_context(
            entry_point,
            user_sp,
            KERNEL_SPACE.lock().token(),
            self.kernel_stack.get_top(),
            trap_handler as usize,
        );
        trap_cx.x[10] = args.len();
        trap_cx.x[11] = argv_base;
        *inner.get_trap_cx() = trap_cx;
        // **** release current PCB lock
    }
    pub fn fork(self: &Arc<TaskControlBlock>) -> Arc<TaskControlBlock> {
        // ---- hold parent PCB lock
        let mut parent_inner = self.acquire_inner_lock();
        // copy user space(include trap context)
        let memory_set = MemorySet::from_existed_user(
            &parent_inner.memory_set
        );
        let trap_cx_ppn = memory_set
            .translate(VirtAddr::from(TRAP_CONTEXT).into())
            .unwrap()
            .ppn();
        // alloc a pid and a kernel stack in kernel space
        let pid_handle = pid_alloc();
        let kernel_stack = KernelStack::new(&pid_handle);
        let kernel_stack_top = kernel_stack.get_top();
        // push a goto_trap_return task_cx on the top of kernel stack
        let task_cx_ptr = kernel_stack.push_on_top(TaskContext::goto_trap_return());
        // copy fd table
        let mut new_fd_table: Vec<Option<Arc<dyn File + Send + Sync>>> = Vec::new();
        for fd in parent_inner.fd_table.iter() {
            if let Some(file) = fd {
                new_fd_table.push(Some(file.clone()));
            } else {
                new_fd_table.push(None);
            }
        }
hm12299's avatar
hm12299 已提交
267
        let name = parent_inner.name.clone();
hm12299's avatar
hm12299 已提交
268
        let ppid = self.pid.0 as isize;
hm12299's avatar
hm12299 已提交
269 270 271
        let task_control_block = Arc::new(TaskControlBlock {
            pid: pid_handle,
            kernel_stack,
hm12299's avatar
hm12299 已提交
272
            ppid,
hm12299's avatar
hm12299 已提交
273 274 275 276 277
            inner: Mutex::new(TaskControlBlockInner {
                trap_cx_ppn,
                base_size: parent_inner.base_size,
                task_cx_ptr: task_cx_ptr as usize,
                task_status: TaskStatus::Ready,
hm12299's avatar
hm12299 已提交
278
                name,
hm12299's avatar
hm12299 已提交
279 280 281 282 283
                memory_set,
                parent: Some(Arc::downgrade(self)),
                children: Vec::new(),
                exit_code: 0,
                fd_table: new_fd_table,
hm12299's avatar
hm12299 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
                start_time: 0,
                cpu_time: 0,
                syscall: Arc::new(Mutex::new(SyscallCount{
                    syscall_dup: (0, 0),
                    syscall_open: (0, 0),
                    syscall_close: (0, 0),
                    syscall_pipe: (0, 0),
                    syscall_read: (0, 0),
                    syscall_write: (0, 0),
                    syscall_exit: (0, 0),
                    syscall_yield: (0, 0),
                    syscall_get_time: (0, 0),
                    syscall_getpid: (0, 0),
                    syscall_fork: (0, 0),
                    syscall_exec: (0, 0),
                    syscall_waitpid: (0, 0),
                }))
301
                // czy
hm12299's avatar
hm12299 已提交
302
                //cpu_time:0,
303
                // czy
hm12299's avatar
hm12299 已提交
304
                //start_run_stamp:0,
hm12299's avatar
hm12299 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
            }),
        });
        // add child
        parent_inner.children.push(task_control_block.clone());
        // modify kernel_sp in trap_cx
        // **** acquire child PCB lock
        let trap_cx = task_control_block.acquire_inner_lock().get_trap_cx();
        // **** release child PCB lock
        trap_cx.kernel_sp = kernel_stack_top;
        // return
        task_control_block
        // ---- release parent PCB lock
    }
    pub fn getpid(&self) -> usize {
        self.pid.0
    }
hm12299's avatar
hm12299 已提交
321 322 323 324 325 326 327

    pub fn get_ppid(&self) -> isize{
        self.ppid
    }

    pub fn get_cpu_time(&self) -> usize{
        self.acquire_inner_lock().cpu_time
C
chenzhiy2001 已提交
328
    }
hm12299's avatar
hm12299 已提交
329 330 331 332

    pub fn get_name(&self) -> String{
        let temp1 = self.acquire_inner_lock();
        temp1.name.clone()
333
    }
hm12299's avatar
hm12299 已提交
334

hm12299's avatar
hm12299 已提交
335 336 337 338 339
    pub fn get_syscall_cnt(&self) -> Arc<Mutex<SyscallCount>>{
        Arc::clone(&self.acquire_inner_lock().syscall) 
    }


hm12299's avatar
hm12299 已提交
340 341 342 343 344 345 346 347
}

#[derive(Copy, Clone, PartialEq)]
pub enum TaskStatus {
    Ready,
    Running,
    Zombie,
}