《操作系统》的实验代码。
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.

855 lines
28 KiB

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