《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

922 regels
29 KiB

12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
  1. #include <proc.h>
  2. #include <kmalloc.h>
  3. #include <string.h>
  4. #include <sync.h>
  5. #include <pmm.h>
  6. #include <error.h>
  7. #include <sched.h>
  8. #include <elf.h>
  9. #include <vmm.h>
  10. #include <trap.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <assert.h>
  14. #include <unistd.h>
  15. #include <fs.h>
  16. #include <vfs.h>
  17. #include <sysfile.h>
  18. /* ------------- process/thread mechanism design&implementation -------------
  19. (an simplified Linux process/thread mechanism )
  20. introduction:
  21. ucore implements a simple process/thread mechanism. process contains the independent memory sapce, at least one threads
  22. for execution, the kernel data(for management), processor state (for context switch), files(in lab6), etc. ucore needs to
  23. manage all these details efficiently. In ucore, a thread is just a special kind of process(share process's memory).
  24. ------------------------------
  25. process state : meaning -- reason
  26. PROC_UNINIT : uninitialized -- alloc_proc
  27. PROC_SLEEPING : sleeping -- try_free_pages, do_wait, do_sleep
  28. PROC_RUNNABLE : runnable(maybe running) -- proc_init, wakeup_proc,
  29. PROC_ZOMBIE : almost dead -- do_exit
  30. -----------------------------
  31. process state changing:
  32. alloc_proc RUNNING
  33. + +--<----<--+
  34. + + proc_run +
  35. V +-->---->--+
  36. PROC_UNINIT -- proc_init/wakeup_proc --> PROC_RUNNABLE -- try_free_pages/do_wait/do_sleep --> PROC_SLEEPING --
  37. A + +
  38. | +--- do_exit --> PROC_ZOMBIE +
  39. + +
  40. -----------------------wakeup_proc----------------------------------
  41. -----------------------------
  42. process relations
  43. parent: proc->parent (proc is children)
  44. children: proc->cptr (proc is parent)
  45. older sibling: proc->optr (proc is younger sibling)
  46. younger sibling: proc->yptr (proc is older sibling)
  47. -----------------------------
  48. related syscall for process:
  49. SYS_exit : process exit, -->do_exit
  50. SYS_fork : create child process, dup mm -->do_fork-->wakeup_proc
  51. SYS_wait : wait process -->do_wait
  52. SYS_exec : after fork, process execute a program -->load a program and refresh the mm
  53. SYS_clone : create child thread -->do_fork-->wakeup_proc
  54. SYS_yield : process flag itself need resecheduling, -- proc->need_sched=1, then scheduler will rescheule this process
  55. SYS_sleep : process sleep -->do_sleep
  56. SYS_kill : kill process -->do_kill-->proc->flags |= PF_EXITING
  57. -->wakeup_proc-->do_wait-->do_exit
  58. SYS_getpid : get the process's pid
  59. */
  60. // the process set's list
  61. list_entry_t proc_list;
  62. #define HASH_SHIFT 10
  63. #define HASH_LIST_SIZE (1 << HASH_SHIFT)
  64. #define pid_hashfn(x) (hash32(x, HASH_SHIFT))
  65. // has list for process set based on pid
  66. static list_entry_t hash_list[HASH_LIST_SIZE];
  67. // idle proc
  68. struct proc_struct *idleproc = NULL;
  69. // init proc
  70. struct proc_struct *initproc = NULL;
  71. // current proc
  72. struct proc_struct *current = NULL;
  73. static int nr_process = 0;
  74. void kernel_thread_entry(void);
  75. void forkrets(struct trapframe *tf);
  76. void switch_to(struct context *from, struct context *to);
  77. // alloc_proc - alloc a proc_struct and init all fields of proc_struct
  78. static struct proc_struct *
  79. alloc_proc(void) {
  80. struct proc_struct *proc = kmalloc(sizeof(struct proc_struct));
  81. if (proc != NULL) {
  82. //LAB4:EXERCISE1 YOUR CODE
  83. /*
  84. * below fields in proc_struct need to be initialized
  85. * enum proc_state state; // Process state
  86. * int pid; // Process ID
  87. * int runs; // the running times of Proces
  88. * uintptr_t kstack; // Process kernel stack
  89. * volatile bool need_resched; // bool value: need to be rescheduled to release CPU?
  90. * struct proc_struct *parent; // the parent process
  91. * struct mm_struct *mm; // Process's memory management field
  92. * struct context context; // Switch here to run process
  93. * struct trapframe *tf; // Trap frame for current interrupt
  94. * uintptr_t cr3; // CR3 register: the base addr of Page Directroy Table(PDT)
  95. * uint32_t flags; // Process flag
  96. * char name[PROC_NAME_LEN + 1]; // Process name
  97. */
  98. //LAB5 YOUR CODE : (update LAB4 steps)
  99. /*
  100. * below fields(add in LAB5) in proc_struct need to be initialized
  101. * uint32_t wait_state; // waiting state
  102. * struct proc_struct *cptr, *yptr, *optr; // relations between processes
  103. */
  104. //LAB6 YOUR CODE : (update LAB5 steps)
  105. /*
  106. * below fields(add in LAB6) in proc_struct need to be initialized
  107. * struct run_queue *rq; // running queue contains Process
  108. * list_entry_t run_link; // the entry linked in run queue
  109. * int time_slice; // time slice for occupying the CPU
  110. * skew_heap_entry_t lab6_run_pool; // FOR LAB6 ONLY: the entry in the run pool
  111. * uint32_t lab6_stride; // FOR LAB6 ONLY: the current stride of the process
  112. * uint32_t lab6_priority; // FOR LAB6 ONLY: the priority of process, set by lab6_set_priority(uint32_t)
  113. */
  114. //LAB8:EXERCISE2 YOUR CODE HINT:need add some code to init fs in proc_struct, ...
  115. }
  116. return proc;
  117. }
  118. // set_proc_name - set the name of proc
  119. char *
  120. set_proc_name(struct proc_struct *proc, const char *name) {
  121. memset(proc->name, 0, sizeof(proc->name));
  122. return memcpy(proc->name, name, PROC_NAME_LEN);
  123. }
  124. // get_proc_name - get the name of proc
  125. char *
  126. get_proc_name(struct proc_struct *proc) {
  127. static char name[PROC_NAME_LEN + 1];
  128. memset(name, 0, sizeof(name));
  129. return memcpy(name, proc->name, PROC_NAME_LEN);
  130. }
  131. // set_links - set the relation links of process
  132. static void
  133. set_links(struct proc_struct *proc) {
  134. list_add(&proc_list, &(proc->list_link));
  135. proc->yptr = NULL;
  136. if ((proc->optr = proc->parent->cptr) != NULL) {
  137. proc->optr->yptr = proc;
  138. }
  139. proc->parent->cptr = proc;
  140. nr_process ++;
  141. }
  142. // remove_links - clean the relation links of process
  143. static void
  144. remove_links(struct proc_struct *proc) {
  145. list_del(&(proc->list_link));
  146. if (proc->optr != NULL) {
  147. proc->optr->yptr = proc->yptr;
  148. }
  149. if (proc->yptr != NULL) {
  150. proc->yptr->optr = proc->optr;
  151. }
  152. else {
  153. proc->parent->cptr = proc->optr;
  154. }
  155. nr_process --;
  156. }
  157. // get_pid - alloc a unique pid for process
  158. static int
  159. get_pid(void) {
  160. static_assert(MAX_PID > MAX_PROCESS);
  161. struct proc_struct *proc;
  162. list_entry_t *list = &proc_list, *le;
  163. static int next_safe = MAX_PID, last_pid = MAX_PID;
  164. if (++ last_pid >= MAX_PID) {
  165. last_pid = 1;
  166. goto inside;
  167. }
  168. if (last_pid >= next_safe) {
  169. inside:
  170. next_safe = MAX_PID;
  171. repeat:
  172. le = list;
  173. while ((le = list_next(le)) != list) {
  174. proc = le2proc(le, list_link);
  175. if (proc->pid == last_pid) {
  176. if (++ last_pid >= next_safe) {
  177. if (last_pid >= MAX_PID) {
  178. last_pid = 1;
  179. }
  180. next_safe = MAX_PID;
  181. goto repeat;
  182. }
  183. }
  184. else if (proc->pid > last_pid && next_safe > proc->pid) {
  185. next_safe = proc->pid;
  186. }
  187. }
  188. }
  189. return last_pid;
  190. }
  191. // proc_run - make process "proc" running on cpu
  192. // NOTE: before call switch_to, should load base addr of "proc"'s new PDT
  193. void
  194. proc_run(struct proc_struct *proc) {
  195. if (proc != current) {
  196. bool intr_flag;
  197. struct proc_struct *prev = current, *next = proc;
  198. local_intr_save(intr_flag);
  199. {
  200. current = proc;
  201. load_esp0(next->kstack + KSTACKSIZE);
  202. lcr3(next->cr3);
  203. switch_to(&(prev->context), &(next->context));
  204. }
  205. local_intr_restore(intr_flag);
  206. }
  207. }
  208. // forkret -- the first kernel entry point of a new thread/process
  209. // NOTE: the addr of forkret is setted in copy_thread function
  210. // after switch_to, the current proc will execute here.
  211. static void
  212. forkret(void) {
  213. forkrets(current->tf);
  214. }
  215. // hash_proc - add proc into proc hash_list
  216. static void
  217. hash_proc(struct proc_struct *proc) {
  218. list_add(hash_list + pid_hashfn(proc->pid), &(proc->hash_link));
  219. }
  220. // unhash_proc - delete proc from proc hash_list
  221. static void
  222. unhash_proc(struct proc_struct *proc) {
  223. list_del(&(proc->hash_link));
  224. }
  225. // find_proc - find proc frome proc hash_list according to pid
  226. struct proc_struct *
  227. find_proc(int pid) {
  228. if (0 < pid && pid < MAX_PID) {
  229. list_entry_t *list = hash_list + pid_hashfn(pid), *le = list;
  230. while ((le = list_next(le)) != list) {
  231. struct proc_struct *proc = le2proc(le, hash_link);
  232. if (proc->pid == pid) {
  233. return proc;
  234. }
  235. }
  236. }
  237. return NULL;
  238. }
  239. // kernel_thread - create a kernel thread using "fn" function
  240. // NOTE: the contents of temp trapframe tf will be copied to
  241. // proc->tf in do_fork-->copy_thread function
  242. int
  243. kernel_thread(int (*fn)(void *), void *arg, uint32_t clone_flags) {
  244. struct trapframe tf;
  245. memset(&tf, 0, sizeof(struct trapframe));
  246. tf.tf_cs = KERNEL_CS;
  247. tf.tf_ds = tf.tf_es = tf.tf_ss = KERNEL_DS;
  248. tf.tf_regs.reg_ebx = (uint32_t)fn;
  249. tf.tf_regs.reg_edx = (uint32_t)arg;
  250. tf.tf_eip = (uint32_t)kernel_thread_entry;
  251. return do_fork(clone_flags | CLONE_VM, 0, &tf);
  252. }
  253. // setup_kstack - alloc pages with size KSTACKPAGE as process kernel stack
  254. static int
  255. setup_kstack(struct proc_struct *proc) {
  256. struct Page *page = alloc_pages(KSTACKPAGE);
  257. if (page != NULL) {
  258. proc->kstack = (uintptr_t)page2kva(page);
  259. return 0;
  260. }
  261. return -E_NO_MEM;
  262. }
  263. // put_kstack - free the memory space of process kernel stack
  264. static void
  265. put_kstack(struct proc_struct *proc) {
  266. free_pages(kva2page((void *)(proc->kstack)), KSTACKPAGE);
  267. }
  268. // setup_pgdir - alloc one page as PDT
  269. static int
  270. setup_pgdir(struct mm_struct *mm) {
  271. struct Page *page;
  272. if ((page = alloc_page()) == NULL) {
  273. return -E_NO_MEM;
  274. }
  275. pde_t *pgdir = page2kva(page);
  276. memcpy(pgdir, boot_pgdir, PGSIZE);
  277. pgdir[PDX(VPT)] = PADDR(pgdir) | PTE_P | PTE_W;
  278. mm->pgdir = pgdir;
  279. return 0;
  280. }
  281. // put_pgdir - free the memory space of PDT
  282. static void
  283. put_pgdir(struct mm_struct *mm) {
  284. free_page(kva2page(mm->pgdir));
  285. }
  286. // copy_mm - process "proc" duplicate OR share process "current"'s mm according clone_flags
  287. // - if clone_flags & CLONE_VM, then "share" ; else "duplicate"
  288. static int
  289. copy_mm(uint32_t clone_flags, struct proc_struct *proc) {
  290. struct mm_struct *mm, *oldmm = current->mm;
  291. /* current is a kernel thread */
  292. if (oldmm == NULL) {
  293. return 0;
  294. }
  295. if (clone_flags & CLONE_VM) {
  296. mm = oldmm;
  297. goto good_mm;
  298. }
  299. int ret = -E_NO_MEM;
  300. if ((mm = mm_create()) == NULL) {
  301. goto bad_mm;
  302. }
  303. if (setup_pgdir(mm) != 0) {
  304. goto bad_pgdir_cleanup_mm;
  305. }
  306. lock_mm(oldmm);
  307. {
  308. ret = dup_mmap(mm, oldmm);
  309. }
  310. unlock_mm(oldmm);
  311. if (ret != 0) {
  312. goto bad_dup_cleanup_mmap;
  313. }
  314. good_mm:
  315. mm_count_inc(mm);
  316. proc->mm = mm;
  317. proc->cr3 = PADDR(mm->pgdir);
  318. return 0;
  319. bad_dup_cleanup_mmap:
  320. exit_mmap(mm);
  321. put_pgdir(mm);
  322. bad_pgdir_cleanup_mm:
  323. mm_destroy(mm);
  324. bad_mm:
  325. return ret;
  326. }
  327. // copy_thread - setup the trapframe on the process's kernel stack top and
  328. // - setup the kernel entry point and stack of process
  329. static void
  330. copy_thread(struct proc_struct *proc, uintptr_t esp, struct trapframe *tf) {
  331. proc->tf = (struct trapframe *)(proc->kstack + KSTACKSIZE) - 1;
  332. *(proc->tf) = *tf;
  333. proc->tf->tf_regs.reg_eax = 0;
  334. proc->tf->tf_esp = esp;
  335. proc->tf->tf_eflags |= FL_IF;
  336. proc->context.eip = (uintptr_t)forkret;
  337. proc->context.esp = (uintptr_t)(proc->tf);
  338. }
  339. //copy_files&put_files function used by do_fork in LAB8
  340. //copy the files_struct from current to proc
  341. static int
  342. copy_files(uint32_t clone_flags, struct proc_struct *proc) {
  343. struct files_struct *filesp, *old_filesp = current->filesp;
  344. assert(old_filesp != NULL);
  345. if (clone_flags & CLONE_FS) {
  346. filesp = old_filesp;
  347. goto good_files_struct;
  348. }
  349. int ret = -E_NO_MEM;
  350. if ((filesp = files_create()) == NULL) {
  351. goto bad_files_struct;
  352. }
  353. if ((ret = dup_files(filesp, old_filesp)) != 0) {
  354. goto bad_dup_cleanup_fs;
  355. }
  356. good_files_struct:
  357. files_count_inc(filesp);
  358. proc->filesp = filesp;
  359. return 0;
  360. bad_dup_cleanup_fs:
  361. files_destroy(filesp);
  362. bad_files_struct:
  363. return ret;
  364. }
  365. //decrease the ref_count of files, and if ref_count==0, then destroy files_struct
  366. static void
  367. put_files(struct proc_struct *proc) {
  368. struct files_struct *filesp = proc->filesp;
  369. if (filesp != NULL) {
  370. if (files_count_dec(filesp) == 0) {
  371. files_destroy(filesp);
  372. }
  373. }
  374. }
  375. /* do_fork - parent process for a new child process
  376. * @clone_flags: used to guide how to clone the child process
  377. * @stack: the parent's user stack pointer. if stack==0, It means to fork a kernel thread.
  378. * @tf: the trapframe info, which will be copied to child process's proc->tf
  379. */
  380. int
  381. do_fork(uint32_t clone_flags, uintptr_t stack, struct trapframe *tf) {
  382. int ret = -E_NO_FREE_PROC;
  383. struct proc_struct *proc;
  384. if (nr_process >= MAX_PROCESS) {
  385. goto fork_out;
  386. }
  387. ret = -E_NO_MEM;
  388. //LAB4:EXERCISE2 YOUR CODE
  389. //LAB8:EXERCISE2 YOUR CODE HINT:how to copy the fs in parent's proc_struct?
  390. /*
  391. * Some Useful MACROs, Functions and DEFINEs, you can use them in below implementation.
  392. * MACROs or Functions:
  393. * alloc_proc: create a proc struct and init fields (lab4:exercise1)
  394. * setup_kstack: alloc pages with size KSTACKPAGE as process kernel stack
  395. * copy_mm: process "proc" duplicate OR share process "current"'s mm according clone_flags
  396. * if clone_flags & CLONE_VM, then "share" ; else "duplicate"
  397. * copy_thread: setup the trapframe on the process's kernel stack top and
  398. * setup the kernel entry point and stack of process
  399. * hash_proc: add proc into proc hash_list
  400. * get_pid: alloc a unique pid for process
  401. * wakup_proc: set proc->state = PROC_RUNNABLE
  402. * VARIABLES:
  403. * proc_list: the process set's list
  404. * nr_process: the number of process set
  405. */
  406. // 1. call alloc_proc to allocate a proc_struct
  407. // 2. call setup_kstack to allocate a kernel stack for child process
  408. // 3. call copy_mm to dup OR share mm according clone_flag
  409. // 4. call copy_thread to setup tf & context in proc_struct
  410. // 5. insert proc_struct into hash_list && proc_list
  411. // 6. call wakup_proc to make the new child process RUNNABLE
  412. // 7. set ret vaule using child proc's pid
  413. //LAB5 YOUR CODE : (update LAB4 steps)
  414. /* Some Functions
  415. * set_links: set the relation links of process. ALSO SEE: remove_links: lean the relation links of process
  416. * -------------------
  417. * update step 1: set child proc's parent to current process, make sure current process's wait_state is 0
  418. * update step 5: insert proc_struct into hash_list && proc_list, set the relation links of process
  419. */
  420. fork_out:
  421. return ret;
  422. bad_fork_cleanup_fs: //for LAB8
  423. put_files(proc);
  424. bad_fork_cleanup_kstack:
  425. put_kstack(proc);
  426. bad_fork_cleanup_proc:
  427. kfree(proc);
  428. goto fork_out;
  429. }
  430. // do_exit - called by sys_exit
  431. // 1. call exit_mmap & put_pgdir & mm_destroy to free the almost all memory space of process
  432. // 2. set process' state as PROC_ZOMBIE, then call wakeup_proc(parent) to ask parent reclaim itself.
  433. // 3. call scheduler to switch to other process
  434. int
  435. do_exit(int error_code) {
  436. if (current == idleproc) {
  437. panic("idleproc exit.\n");
  438. }
  439. if (current == initproc) {
  440. panic("initproc exit.\n");
  441. }
  442. struct mm_struct *mm = current->mm;
  443. if (mm != NULL) {
  444. lcr3(boot_cr3);
  445. if (mm_count_dec(mm) == 0) {
  446. exit_mmap(mm);
  447. put_pgdir(mm);
  448. mm_destroy(mm);
  449. }
  450. current->mm = NULL;
  451. }
  452. put_files(current); //for LAB8
  453. current->state = PROC_ZOMBIE;
  454. current->exit_code = error_code;
  455. bool intr_flag;
  456. struct proc_struct *proc;
  457. local_intr_save(intr_flag);
  458. {
  459. proc = current->parent;
  460. if (proc->wait_state == WT_CHILD) {
  461. wakeup_proc(proc);
  462. }
  463. while (current->cptr != NULL) {
  464. proc = current->cptr;
  465. current->cptr = proc->optr;
  466. proc->yptr = NULL;
  467. if ((proc->optr = initproc->cptr) != NULL) {
  468. initproc->cptr->yptr = proc;
  469. }
  470. proc->parent = initproc;
  471. initproc->cptr = proc;
  472. if (proc->state == PROC_ZOMBIE) {
  473. if (initproc->wait_state == WT_CHILD) {
  474. wakeup_proc(initproc);
  475. }
  476. }
  477. }
  478. }
  479. local_intr_restore(intr_flag);
  480. schedule();
  481. panic("do_exit will not return!! %d.\n", current->pid);
  482. }
  483. //load_icode_read is used by load_icode in LAB8
  484. static int
  485. load_icode_read(int fd, void *buf, size_t len, off_t offset) {
  486. int ret;
  487. if ((ret = sysfile_seek(fd, offset, LSEEK_SET)) != 0) {
  488. return ret;
  489. }
  490. if ((ret = sysfile_read(fd, buf, len)) != len) {
  491. return (ret < 0) ? ret : -1;
  492. }
  493. return 0;
  494. }
  495. // load_icode - called by sys_exec-->do_execve
  496. static int
  497. load_icode(int fd, int argc, char **kargv) {
  498. /* LAB8:EXERCISE2 YOUR CODE HINT:how to load the file with handler fd in to process's memory? how to setup argc/argv?
  499. * MACROs or Functions:
  500. * mm_create - create a mm
  501. * setup_pgdir - setup pgdir in mm
  502. * load_icode_read - read raw data content of program file
  503. * mm_map - build new vma
  504. * pgdir_alloc_page - allocate new memory for TEXT/DATA/BSS/stack parts
  505. * lcr3 - update Page Directory Addr Register -- CR3
  506. */
  507. /* (1) create a new mm for current process
  508. * (2) create a new PDT, and mm->pgdir= kernel virtual addr of PDT
  509. * (3) copy TEXT/DATA/BSS parts in binary to memory space of process
  510. * (3.1) read raw data content in file and resolve elfhdr
  511. * (3.2) read raw data content in file and resolve proghdr based on info in elfhdr
  512. * (3.3) call mm_map to build vma related to TEXT/DATA
  513. * (3.4) callpgdir_alloc_page to allocate page for TEXT/DATA, read contents in file
  514. * and copy them into the new allocated pages
  515. * (3.5) callpgdir_alloc_page to allocate pages for BSS, memset zero in these pages
  516. * (4) call mm_map to setup user stack, and put parameters into user stack
  517. * (5) setup current process's mm, cr3, reset pgidr (using lcr3 MARCO)
  518. * (6) setup uargc and uargv in user stacks
  519. * (7) setup trapframe for user environment
  520. * (8) if up steps failed, you should cleanup the env.
  521. */
  522. }
  523. // this function isn't very correct in LAB8
  524. static void
  525. put_kargv(int argc, char **kargv) {
  526. while (argc > 0) {
  527. kfree(kargv[-- argc]);
  528. }
  529. }
  530. static int
  531. copy_kargv(struct mm_struct *mm, int argc, char **kargv, const char **argv) {
  532. int i, ret = -E_INVAL;
  533. if (!user_mem_check(mm, (uintptr_t)argv, sizeof(const char *) * argc, 0)) {
  534. return ret;
  535. }
  536. for (i = 0; i < argc; i ++) {
  537. char *buffer;
  538. if ((buffer = kmalloc(EXEC_MAX_ARG_LEN + 1)) == NULL) {
  539. goto failed_nomem;
  540. }
  541. if (!copy_string(mm, buffer, argv[i], EXEC_MAX_ARG_LEN + 1)) {
  542. kfree(buffer);
  543. goto failed_cleanup;
  544. }
  545. kargv[i] = buffer;
  546. }
  547. return 0;
  548. failed_nomem:
  549. ret = -E_NO_MEM;
  550. failed_cleanup:
  551. put_kargv(i, kargv);
  552. return ret;
  553. }
  554. // do_execve - call exit_mmap(mm)&pug_pgdir(mm) to reclaim memory space of current process
  555. // - call load_icode to setup new memory space accroding binary prog.
  556. int
  557. do_execve(const char *name, int argc, const char **argv) {
  558. static_assert(EXEC_MAX_ARG_LEN >= FS_MAX_FPATH_LEN);
  559. struct mm_struct *mm = current->mm;
  560. if (!(argc >= 1 && argc <= EXEC_MAX_ARG_NUM)) {
  561. return -E_INVAL;
  562. }
  563. char local_name[PROC_NAME_LEN + 1];
  564. memset(local_name, 0, sizeof(local_name));
  565. char *kargv[EXEC_MAX_ARG_NUM];
  566. const char *path;
  567. int ret = -E_INVAL;
  568. lock_mm(mm);
  569. if (name == NULL) {
  570. snprintf(local_name, sizeof(local_name), "<null> %d", current->pid);
  571. }
  572. else {
  573. if (!copy_string(mm, local_name, name, sizeof(local_name))) {
  574. unlock_mm(mm);
  575. return ret;
  576. }
  577. }
  578. if ((ret = copy_kargv(mm, argc, kargv, argv)) != 0) {
  579. unlock_mm(mm);
  580. return ret;
  581. }
  582. path = argv[0];
  583. unlock_mm(mm);
  584. files_closeall(current->filesp);
  585. /* sysfile_open will check the first argument path, thus we have to use a user-space pointer, and argv[0] may be incorrect */
  586. int fd;
  587. if ((ret = fd = sysfile_open(path, O_RDONLY)) < 0) {
  588. goto execve_exit;
  589. }
  590. if (mm != NULL) {
  591. lcr3(boot_cr3);
  592. if (mm_count_dec(mm) == 0) {
  593. exit_mmap(mm);
  594. put_pgdir(mm);
  595. mm_destroy(mm);
  596. }
  597. current->mm = NULL;
  598. }
  599. ret= -E_NO_MEM;;
  600. if ((ret = load_icode(fd, argc, kargv)) != 0) {
  601. goto execve_exit;
  602. }
  603. put_kargv(argc, kargv);
  604. set_proc_name(current, local_name);
  605. return 0;
  606. execve_exit:
  607. put_kargv(argc, kargv);
  608. do_exit(ret);
  609. panic("already exit: %e.\n", ret);
  610. }
  611. // do_yield - ask the scheduler to reschedule
  612. int
  613. do_yield(void) {
  614. current->need_resched = 1;
  615. return 0;
  616. }
  617. // do_wait - wait one OR any children with PROC_ZOMBIE state, and free memory space of kernel stack
  618. // - proc struct of this child.
  619. // NOTE: only after do_wait function, all resources of the child proces are free.
  620. int
  621. do_wait(int pid, int *code_store) {
  622. struct mm_struct *mm = current->mm;
  623. if (code_store != NULL) {
  624. if (!user_mem_check(mm, (uintptr_t)code_store, sizeof(int), 1)) {
  625. return -E_INVAL;
  626. }
  627. }
  628. struct proc_struct *proc;
  629. bool intr_flag, haskid;
  630. repeat:
  631. haskid = 0;
  632. if (pid != 0) {
  633. proc = find_proc(pid);
  634. if (proc != NULL && proc->parent == current) {
  635. haskid = 1;
  636. if (proc->state == PROC_ZOMBIE) {
  637. goto found;
  638. }
  639. }
  640. }
  641. else {
  642. proc = current->cptr;
  643. for (; proc != NULL; proc = proc->optr) {
  644. haskid = 1;
  645. if (proc->state == PROC_ZOMBIE) {
  646. goto found;
  647. }
  648. }
  649. }
  650. if (haskid) {
  651. current->state = PROC_SLEEPING;
  652. current->wait_state = WT_CHILD;
  653. schedule();
  654. if (current->flags & PF_EXITING) {
  655. do_exit(-E_KILLED);
  656. }
  657. goto repeat;
  658. }
  659. return -E_BAD_PROC;
  660. found:
  661. if (proc == idleproc || proc == initproc) {
  662. panic("wait idleproc or initproc.\n");
  663. }
  664. if (code_store != NULL) {
  665. *code_store = proc->exit_code;
  666. }
  667. local_intr_save(intr_flag);
  668. {
  669. unhash_proc(proc);
  670. remove_links(proc);
  671. }
  672. local_intr_restore(intr_flag);
  673. put_kstack(proc);
  674. kfree(proc);
  675. return 0;
  676. }
  677. // do_kill - kill process with pid by set this process's flags with PF_EXITING
  678. int
  679. do_kill(int pid) {
  680. struct proc_struct *proc;
  681. if ((proc = find_proc(pid)) != NULL) {
  682. if (!(proc->flags & PF_EXITING)) {
  683. proc->flags |= PF_EXITING;
  684. if (proc->wait_state & WT_INTERRUPTED) {
  685. wakeup_proc(proc);
  686. }
  687. return 0;
  688. }
  689. return -E_KILLED;
  690. }
  691. return -E_INVAL;
  692. }
  693. // kernel_execve - do SYS_exec syscall to exec a user program called by user_main kernel_thread
  694. static int
  695. kernel_execve(const char *name, const char **argv) {
  696. int argc = 0, ret;
  697. while (argv[argc] != NULL) {
  698. argc ++;
  699. }
  700. asm volatile (
  701. "int %1;"
  702. : "=a" (ret)
  703. : "i" (T_SYSCALL), "0" (SYS_exec), "d" (name), "c" (argc), "b" (argv)
  704. : "memory");
  705. return ret;
  706. }
  707. #define __KERNEL_EXECVE(name, path, ...) ({ \
  708. const char *argv[] = {path, ##__VA_ARGS__, NULL}; \
  709. cprintf("kernel_execve: pid = %d, name = \"%s\".\n", \
  710. current->pid, name); \
  711. kernel_execve(name, argv); \
  712. })
  713. #define KERNEL_EXECVE(x, ...) __KERNEL_EXECVE(#x, #x, ##__VA_ARGS__)
  714. #define KERNEL_EXECVE2(x, ...) KERNEL_EXECVE(x, ##__VA_ARGS__)
  715. #define __KERNEL_EXECVE3(x, s, ...) KERNEL_EXECVE(x, #s, ##__VA_ARGS__)
  716. #define KERNEL_EXECVE3(x, s, ...) __KERNEL_EXECVE3(x, s, ##__VA_ARGS__)
  717. // user_main - kernel thread used to exec a user program
  718. static int
  719. user_main(void *arg) {
  720. #ifdef TEST
  721. #ifdef TESTSCRIPT
  722. KERNEL_EXECVE3(TEST, TESTSCRIPT);
  723. #else
  724. KERNEL_EXECVE2(TEST);
  725. #endif
  726. #else
  727. KERNEL_EXECVE(sh);
  728. #endif
  729. panic("user_main execve failed.\n");
  730. }
  731. // init_main - the second kernel thread used to create user_main kernel threads
  732. static int
  733. init_main(void *arg) {
  734. int ret;
  735. if ((ret = vfs_set_bootfs("disk0:")) != 0) {
  736. panic("set boot fs failed: %e.\n", ret);
  737. }
  738. size_t nr_free_pages_store = nr_free_pages();
  739. size_t kernel_allocated_store = kallocated();
  740. int pid = kernel_thread(user_main, NULL, 0);
  741. if (pid <= 0) {
  742. panic("create user_main failed.\n");
  743. }
  744. extern void check_sync(void);
  745. check_sync(); // check philosopher sync problem
  746. while (do_wait(0, NULL) == 0) {
  747. schedule();
  748. }
  749. fs_cleanup();
  750. cprintf("all user-mode processes have quit.\n");
  751. assert(initproc->cptr == NULL && initproc->yptr == NULL && initproc->optr == NULL);
  752. assert(nr_process == 2);
  753. assert(list_next(&proc_list) == &(initproc->list_link));
  754. assert(list_prev(&proc_list) == &(initproc->list_link));
  755. cprintf("init check memory pass.\n");
  756. return 0;
  757. }
  758. // proc_init - set up the first kernel thread idleproc "idle" by itself and
  759. // - create the second kernel thread init_main
  760. void
  761. proc_init(void) {
  762. int i;
  763. list_init(&proc_list);
  764. for (i = 0; i < HASH_LIST_SIZE; i ++) {
  765. list_init(hash_list + i);
  766. }
  767. if ((idleproc = alloc_proc()) == NULL) {
  768. panic("cannot alloc idleproc.\n");
  769. }
  770. idleproc->pid = 0;
  771. idleproc->state = PROC_RUNNABLE;
  772. idleproc->kstack = (uintptr_t)bootstack;
  773. idleproc->need_resched = 1;
  774. if ((idleproc->filesp = files_create()) == NULL) {
  775. panic("create filesp (idleproc) failed.\n");
  776. }
  777. files_count_inc(idleproc->filesp);
  778. set_proc_name(idleproc, "idle");
  779. nr_process ++;
  780. current = idleproc;
  781. int pid = kernel_thread(init_main, NULL, 0);
  782. if (pid <= 0) {
  783. panic("create init_main failed.\n");
  784. }
  785. initproc = find_proc(pid);
  786. set_proc_name(initproc, "init");
  787. assert(idleproc != NULL && idleproc->pid == 0);
  788. assert(initproc != NULL && initproc->pid == 1);
  789. }
  790. // cpu_idle - at the end of kern_init, the first kernel thread idleproc will do below works
  791. void
  792. cpu_idle(void) {
  793. while (1) {
  794. if (current->need_resched) {
  795. schedule();
  796. }
  797. }
  798. }
  799. //FOR LAB6, set the process's priority (bigger value will get more CPU time)
  800. void
  801. lab6_set_priority(uint32_t priority)
  802. {
  803. if (priority == 0)
  804. current->lab6_priority = 1;
  805. else current->lab6_priority = priority;
  806. }
  807. // do_sleep - set current process state to sleep and add timer with "time"
  808. // - then call scheduler. if process run again, delete timer first.
  809. int
  810. do_sleep(unsigned int time) {
  811. if (time == 0) {
  812. return 0;
  813. }
  814. bool intr_flag;
  815. local_intr_save(intr_flag);
  816. timer_t __timer, *timer = timer_init(&__timer, current, time);
  817. current->state = PROC_SLEEPING;
  818. current->wait_state = WT_TIMER;
  819. add_timer(timer);
  820. local_intr_restore(intr_flag);
  821. schedule();
  822. del_timer(timer);
  823. return 0;
  824. }