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

902 lines
29 KiB

10 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. proc->state = PROC_UNINIT;
  96. proc->pid = -1;
  97. proc->runs = 0;
  98. proc->kstack = 0;
  99. proc->need_resched = 0;
  100. proc->parent = NULL;
  101. proc->mm = NULL;
  102. memset(&(proc->context), 0, sizeof(struct context));
  103. proc->tf = NULL;
  104. proc->cr3 = boot_cr3;
  105. proc->flags = 0;
  106. memset(proc->name, 0, PROC_NAME_LEN);
  107. proc->wait_state = 0;
  108. proc->cptr = proc->optr = proc->yptr = NULL;
  109. proc->rq = NULL;
  110. proc->run_link.prev = proc->run_link.next = NULL;
  111. proc->time_slice = 0;
  112. proc->lab6_run_pool.left = proc->lab6_run_pool.right = proc->lab6_run_pool.parent = NULL;
  113. proc->lab6_stride = 0;
  114. proc->lab6_priority = 0;
  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. /* do_fork - parent process for a new child process
  340. * @clone_flags: used to guide how to clone the child process
  341. * @stack: the parent's user stack pointer. if stack==0, It means to fork a kernel thread.
  342. * @tf: the trapframe info, which will be copied to child process's proc->tf
  343. */
  344. int
  345. do_fork(uint32_t clone_flags, uintptr_t stack, struct trapframe *tf) {
  346. int ret = -E_NO_FREE_PROC;
  347. struct proc_struct *proc;
  348. if (nr_process >= MAX_PROCESS) {
  349. goto fork_out;
  350. }
  351. ret = -E_NO_MEM;
  352. //LAB4:EXERCISE2 YOUR CODE
  353. /*
  354. * Some Useful MACROs, Functions and DEFINEs, you can use them in below implementation.
  355. * MACROs or Functions:
  356. * alloc_proc: create a proc struct and init fields (lab4:exercise1)
  357. * setup_kstack: alloc pages with size KSTACKPAGE as process kernel stack
  358. * copy_mm: process "proc" duplicate OR share process "current"'s mm according clone_flags
  359. * if clone_flags & CLONE_VM, then "share" ; else "duplicate"
  360. * copy_thread: setup the trapframe on the process's kernel stack top and
  361. * setup the kernel entry point and stack of process
  362. * hash_proc: add proc into proc hash_list
  363. * get_pid: alloc a unique pid for process
  364. * wakup_proc: set proc->state = PROC_RUNNABLE
  365. * VARIABLES:
  366. * proc_list: the process set's list
  367. * nr_process: the number of process set
  368. */
  369. // 1. call alloc_proc to allocate a proc_struct
  370. // 2. call setup_kstack to allocate a kernel stack for child process
  371. // 3. call copy_mm to dup OR share mm according clone_flag
  372. // 4. call copy_thread to setup tf & context in proc_struct
  373. // 5. insert proc_struct into hash_list && proc_list
  374. // 6. call wakup_proc to make the new child process RUNNABLE
  375. // 7. set ret vaule using child proc's pid
  376. if ((proc = alloc_proc()) == NULL) {
  377. goto fork_out;
  378. }
  379. proc->parent = current;
  380. assert(current->wait_state == 0);
  381. if (setup_kstack(proc) != 0) {
  382. goto bad_fork_cleanup_proc;
  383. }
  384. if (copy_mm(clone_flags, proc) != 0) {
  385. goto bad_fork_cleanup_kstack;
  386. }
  387. copy_thread(proc, stack, tf);
  388. bool intr_flag;
  389. local_intr_save(intr_flag);
  390. {
  391. proc->pid = get_pid();
  392. hash_proc(proc);
  393. set_links(proc);
  394. }
  395. local_intr_restore(intr_flag);
  396. wakeup_proc(proc);
  397. ret = proc->pid;
  398. fork_out:
  399. return ret;
  400. bad_fork_cleanup_kstack:
  401. put_kstack(proc);
  402. bad_fork_cleanup_proc:
  403. kfree(proc);
  404. goto fork_out;
  405. }
  406. // do_exit - called by sys_exit
  407. // 1. call exit_mmap & put_pgdir & mm_destroy to free the almost all memory space of process
  408. // 2. set process' state as PROC_ZOMBIE, then call wakeup_proc(parent) to ask parent reclaim itself.
  409. // 3. call scheduler to switch to other process
  410. int
  411. do_exit(int error_code) {
  412. if (current == idleproc) {
  413. panic("idleproc exit.\n");
  414. }
  415. if (current == initproc) {
  416. panic("initproc exit.\n");
  417. }
  418. struct mm_struct *mm = current->mm;
  419. if (mm != NULL) {
  420. lcr3(boot_cr3);
  421. if (mm_count_dec(mm) == 0) {
  422. exit_mmap(mm);
  423. put_pgdir(mm);
  424. mm_destroy(mm);
  425. }
  426. current->mm = NULL;
  427. }
  428. current->state = PROC_ZOMBIE;
  429. current->exit_code = error_code;
  430. bool intr_flag;
  431. struct proc_struct *proc;
  432. local_intr_save(intr_flag);
  433. {
  434. proc = current->parent;
  435. if (proc->wait_state == WT_CHILD) {
  436. wakeup_proc(proc);
  437. }
  438. while (current->cptr != NULL) {
  439. proc = current->cptr;
  440. current->cptr = proc->optr;
  441. proc->yptr = NULL;
  442. if ((proc->optr = initproc->cptr) != NULL) {
  443. initproc->cptr->yptr = proc;
  444. }
  445. proc->parent = initproc;
  446. initproc->cptr = proc;
  447. if (proc->state == PROC_ZOMBIE) {
  448. if (initproc->wait_state == WT_CHILD) {
  449. wakeup_proc(initproc);
  450. }
  451. }
  452. }
  453. }
  454. local_intr_restore(intr_flag);
  455. schedule();
  456. panic("do_exit will not return!! %d.\n", current->pid);
  457. }
  458. /* load_icode - load the content of binary program(ELF format) as the new content of current process
  459. * @binary: the memory addr of the content of binary program
  460. * @size: the size of the content of binary program
  461. */
  462. static int
  463. load_icode(unsigned char *binary, size_t size) {
  464. if (current->mm != NULL) {
  465. panic("load_icode: current->mm must be empty.\n");
  466. }
  467. int ret = -E_NO_MEM;
  468. struct mm_struct *mm;
  469. //(1) create a new mm for current process
  470. if ((mm = mm_create()) == NULL) {
  471. goto bad_mm;
  472. }
  473. //(2) create a new PDT, and mm->pgdir= kernel virtual addr of PDT
  474. if (setup_pgdir(mm) != 0) {
  475. goto bad_pgdir_cleanup_mm;
  476. }
  477. //(3) copy TEXT/DATA section, build BSS parts in binary to memory space of process
  478. struct Page *page;
  479. //(3.1) get the file header of the bianry program (ELF format)
  480. struct elfhdr *elf = (struct elfhdr *)binary;
  481. //(3.2) get the entry of the program section headers of the bianry program (ELF format)
  482. struct proghdr *ph = (struct proghdr *)(binary + elf->e_phoff);
  483. //(3.3) This program is valid?
  484. if (elf->e_magic != ELF_MAGIC) {
  485. ret = -E_INVAL_ELF;
  486. goto bad_elf_cleanup_pgdir;
  487. }
  488. uint32_t vm_flags, perm;
  489. struct proghdr *ph_end = ph + elf->e_phnum;
  490. for (; ph < ph_end; ph ++) {
  491. //(3.4) find every program section headers
  492. if (ph->p_type != ELF_PT_LOAD) {
  493. continue ;
  494. }
  495. if (ph->p_filesz > ph->p_memsz) {
  496. ret = -E_INVAL_ELF;
  497. goto bad_cleanup_mmap;
  498. }
  499. if (ph->p_filesz == 0) {
  500. continue ;
  501. }
  502. //(3.5) call mm_map fun to setup the new vma ( ph->p_va, ph->p_memsz)
  503. vm_flags = 0, perm = PTE_U;
  504. if (ph->p_flags & ELF_PF_X) vm_flags |= VM_EXEC;
  505. if (ph->p_flags & ELF_PF_W) vm_flags |= VM_WRITE;
  506. if (ph->p_flags & ELF_PF_R) vm_flags |= VM_READ;
  507. if (vm_flags & VM_WRITE) perm |= PTE_W;
  508. if ((ret = mm_map(mm, ph->p_va, ph->p_memsz, vm_flags, NULL)) != 0) {
  509. goto bad_cleanup_mmap;
  510. }
  511. unsigned char *from = binary + ph->p_offset;
  512. size_t off, size;
  513. uintptr_t start = ph->p_va, end, la = ROUNDDOWN(start, PGSIZE);
  514. ret = -E_NO_MEM;
  515. //(3.6) alloc memory, and copy the contents of every program section (from, from+end) to process's memory (la, la+end)
  516. end = ph->p_va + ph->p_filesz;
  517. //(3.6.1) copy TEXT/DATA section of bianry program
  518. while (start < end) {
  519. if ((page = pgdir_alloc_page(mm->pgdir, la, perm)) == NULL) {
  520. goto bad_cleanup_mmap;
  521. }
  522. off = start - la, size = PGSIZE - off, la += PGSIZE;
  523. if (end < la) {
  524. size -= la - end;
  525. }
  526. memcpy(page2kva(page) + off, from, size);
  527. start += size, from += size;
  528. }
  529. //(3.6.2) build BSS section of binary program
  530. end = ph->p_va + ph->p_memsz;
  531. if (start < la) {
  532. /* ph->p_memsz == ph->p_filesz */
  533. if (start == end) {
  534. continue ;
  535. }
  536. off = start + PGSIZE - la, size = PGSIZE - off;
  537. if (end < la) {
  538. size -= la - end;
  539. }
  540. memset(page2kva(page) + off, 0, size);
  541. start += size;
  542. assert((end < la && start == end) || (end >= la && start == la));
  543. }
  544. while (start < end) {
  545. if ((page = pgdir_alloc_page(mm->pgdir, la, perm)) == NULL) {
  546. goto bad_cleanup_mmap;
  547. }
  548. off = start - la, size = PGSIZE - off, la += PGSIZE;
  549. if (end < la) {
  550. size -= la - end;
  551. }
  552. memset(page2kva(page) + off, 0, size);
  553. start += size;
  554. }
  555. }
  556. //(4) build user stack memory
  557. vm_flags = VM_READ | VM_WRITE | VM_STACK;
  558. if ((ret = mm_map(mm, USTACKTOP - USTACKSIZE, USTACKSIZE, vm_flags, NULL)) != 0) {
  559. goto bad_cleanup_mmap;
  560. }
  561. assert(pgdir_alloc_page(mm->pgdir, USTACKTOP-PGSIZE , PTE_USER) != NULL);
  562. assert(pgdir_alloc_page(mm->pgdir, USTACKTOP-2*PGSIZE , PTE_USER) != NULL);
  563. assert(pgdir_alloc_page(mm->pgdir, USTACKTOP-3*PGSIZE , PTE_USER) != NULL);
  564. assert(pgdir_alloc_page(mm->pgdir, USTACKTOP-4*PGSIZE , PTE_USER) != NULL);
  565. //(5) set current process's mm, sr3, and set CR3 reg = physical addr of Page Directory
  566. mm_count_inc(mm);
  567. current->mm = mm;
  568. current->cr3 = PADDR(mm->pgdir);
  569. lcr3(PADDR(mm->pgdir));
  570. //(6) setup trapframe for user environment
  571. struct trapframe *tf = current->tf;
  572. memset(tf, 0, sizeof(struct trapframe));
  573. /* LAB5:EXERCISE1 YOUR CODE
  574. * should set tf_cs,tf_ds,tf_es,tf_ss,tf_esp,tf_eip,tf_eflags
  575. * NOTICE: If we set trapframe correctly, then the user level process can return to USER MODE from kernel. So
  576. * tf_cs should be USER_CS segment (see memlayout.h)
  577. * tf_ds=tf_es=tf_ss should be USER_DS segment
  578. * tf_esp should be the top addr of user stack (USTACKTOP)
  579. * tf_eip should be the entry point of this binary program (elf->e_entry)
  580. * tf_eflags should be set to enable computer to produce Interrupt
  581. */
  582. tf->tf_cs = USER_CS;
  583. tf->tf_ds = tf->tf_es = tf->tf_ss = USER_DS;
  584. tf->tf_esp = USTACKTOP;
  585. tf->tf_eip = elf->e_entry;
  586. tf->tf_eflags = FL_IF;
  587. ret = 0;
  588. out:
  589. return ret;
  590. bad_cleanup_mmap:
  591. exit_mmap(mm);
  592. bad_elf_cleanup_pgdir:
  593. put_pgdir(mm);
  594. bad_pgdir_cleanup_mm:
  595. mm_destroy(mm);
  596. bad_mm:
  597. goto out;
  598. }
  599. // do_execve - call exit_mmap(mm)&pug_pgdir(mm) to reclaim memory space of current process
  600. // - call load_icode to setup new memory space accroding binary prog.
  601. int
  602. do_execve(const char *name, size_t len, unsigned char *binary, size_t size) {
  603. struct mm_struct *mm = current->mm;
  604. if (!user_mem_check(mm, (uintptr_t)name, len, 0)) {
  605. return -E_INVAL;
  606. }
  607. if (len > PROC_NAME_LEN) {
  608. len = PROC_NAME_LEN;
  609. }
  610. char local_name[PROC_NAME_LEN + 1];
  611. memset(local_name, 0, sizeof(local_name));
  612. memcpy(local_name, name, len);
  613. if (mm != NULL) {
  614. lcr3(boot_cr3);
  615. if (mm_count_dec(mm) == 0) {
  616. exit_mmap(mm);
  617. put_pgdir(mm);
  618. mm_destroy(mm);
  619. }
  620. current->mm = NULL;
  621. }
  622. int ret;
  623. if ((ret = load_icode(binary, size)) != 0) {
  624. goto execve_exit;
  625. }
  626. set_proc_name(current, local_name);
  627. return 0;
  628. execve_exit:
  629. do_exit(ret);
  630. panic("already exit: %e.\n", ret);
  631. }
  632. // do_yield - ask the scheduler to reschedule
  633. int
  634. do_yield(void) {
  635. current->need_resched = 1;
  636. return 0;
  637. }
  638. // do_wait - wait one OR any children with PROC_ZOMBIE state, and free memory space of kernel stack
  639. // - proc struct of this child.
  640. // NOTE: only after do_wait function, all resources of the child proces are free.
  641. int
  642. do_wait(int pid, int *code_store) {
  643. struct mm_struct *mm = current->mm;
  644. if (code_store != NULL) {
  645. if (!user_mem_check(mm, (uintptr_t)code_store, sizeof(int), 1)) {
  646. return -E_INVAL;
  647. }
  648. }
  649. struct proc_struct *proc;
  650. bool intr_flag, haskid;
  651. repeat:
  652. haskid = 0;
  653. if (pid != 0) {
  654. proc = find_proc(pid);
  655. if (proc != NULL && proc->parent == current) {
  656. haskid = 1;
  657. if (proc->state == PROC_ZOMBIE) {
  658. goto found;
  659. }
  660. }
  661. }
  662. else {
  663. proc = current->cptr;
  664. for (; proc != NULL; proc = proc->optr) {
  665. haskid = 1;
  666. if (proc->state == PROC_ZOMBIE) {
  667. goto found;
  668. }
  669. }
  670. }
  671. if (haskid) {
  672. current->state = PROC_SLEEPING;
  673. current->wait_state = WT_CHILD;
  674. schedule();
  675. if (current->flags & PF_EXITING) {
  676. do_exit(-E_KILLED);
  677. }
  678. goto repeat;
  679. }
  680. return -E_BAD_PROC;
  681. found:
  682. if (proc == idleproc || proc == initproc) {
  683. panic("wait idleproc or initproc.\n");
  684. }
  685. if (code_store != NULL) {
  686. *code_store = proc->exit_code;
  687. }
  688. local_intr_save(intr_flag);
  689. {
  690. unhash_proc(proc);
  691. remove_links(proc);
  692. }
  693. local_intr_restore(intr_flag);
  694. put_kstack(proc);
  695. kfree(proc);
  696. return 0;
  697. }
  698. // do_kill - kill process with pid by set this process's flags with PF_EXITING
  699. int
  700. do_kill(int pid) {
  701. struct proc_struct *proc;
  702. if ((proc = find_proc(pid)) != NULL) {
  703. if (!(proc->flags & PF_EXITING)) {
  704. proc->flags |= PF_EXITING;
  705. if (proc->wait_state & WT_INTERRUPTED) {
  706. wakeup_proc(proc);
  707. }
  708. return 0;
  709. }
  710. return -E_KILLED;
  711. }
  712. return -E_INVAL;
  713. }
  714. // kernel_execve - do SYS_exec syscall to exec a user program called by user_main kernel_thread
  715. static int
  716. kernel_execve(const char *name, unsigned char *binary, size_t size) {
  717. int ret, len = strlen(name);
  718. asm volatile (
  719. "int %1;"
  720. : "=a" (ret)
  721. : "i" (T_SYSCALL), "0" (SYS_exec), "d" (name), "c" (len), "b" (binary), "D" (size)
  722. : "memory");
  723. return ret;
  724. }
  725. #define __KERNEL_EXECVE(name, binary, size) ({ \
  726. cprintf("kernel_execve: pid = %d, name = \"%s\".\n", \
  727. current->pid, name); \
  728. kernel_execve(name, binary, (size_t)(size)); \
  729. })
  730. #define KERNEL_EXECVE(x) ({ \
  731. extern unsigned char _binary_obj___user_##x##_out_start[], \
  732. _binary_obj___user_##x##_out_size[]; \
  733. __KERNEL_EXECVE(#x, _binary_obj___user_##x##_out_start, \
  734. _binary_obj___user_##x##_out_size); \
  735. })
  736. #define __KERNEL_EXECVE2(x, xstart, xsize) ({ \
  737. extern unsigned char xstart[], xsize[]; \
  738. __KERNEL_EXECVE(#x, xstart, (size_t)xsize); \
  739. })
  740. #define KERNEL_EXECVE2(x, xstart, xsize) __KERNEL_EXECVE2(x, xstart, xsize)
  741. // user_main - kernel thread used to exec a user program
  742. static int
  743. user_main(void *arg) {
  744. #ifdef TEST
  745. KERNEL_EXECVE2(TEST, TESTSTART, TESTSIZE);
  746. #else
  747. KERNEL_EXECVE(exit);
  748. #endif
  749. panic("user_main execve failed.\n");
  750. }
  751. // init_main - the second kernel thread used to create user_main kernel threads
  752. static int
  753. init_main(void *arg) {
  754. size_t nr_free_pages_store = nr_free_pages();
  755. size_t kernel_allocated_store = kallocated();
  756. int pid = kernel_thread(user_main, NULL, 0);
  757. if (pid <= 0) {
  758. panic("create user_main failed.\n");
  759. }
  760. while (do_wait(0, NULL) == 0) {
  761. schedule();
  762. }
  763. cprintf("all user-mode processes have quit.\n");
  764. assert(initproc->cptr == NULL && initproc->yptr == NULL && initproc->optr == NULL);
  765. assert(nr_process == 2);
  766. assert(list_next(&proc_list) == &(initproc->list_link));
  767. assert(list_prev(&proc_list) == &(initproc->list_link));
  768. assert(nr_free_pages_store == nr_free_pages());
  769. assert(kernel_allocated_store == kallocated());
  770. cprintf("init check memory pass.\n");
  771. return 0;
  772. }
  773. // proc_init - set up the first kernel thread idleproc "idle" by itself and
  774. // - create the second kernel thread init_main
  775. void
  776. proc_init(void) {
  777. int i;
  778. list_init(&proc_list);
  779. for (i = 0; i < HASH_LIST_SIZE; i ++) {
  780. list_init(hash_list + i);
  781. }
  782. if ((idleproc = alloc_proc()) == NULL) {
  783. panic("cannot alloc idleproc.\n");
  784. }
  785. idleproc->pid = 0;
  786. idleproc->state = PROC_RUNNABLE;
  787. idleproc->kstack = (uintptr_t)bootstack;
  788. idleproc->need_resched = 1;
  789. set_proc_name(idleproc, "idle");
  790. nr_process ++;
  791. current = idleproc;
  792. int pid = kernel_thread(init_main, NULL, 0);
  793. if (pid <= 0) {
  794. panic("create init_main failed.\n");
  795. }
  796. initproc = find_proc(pid);
  797. set_proc_name(initproc, "init");
  798. assert(idleproc != NULL && idleproc->pid == 0);
  799. assert(initproc != NULL && initproc->pid == 1);
  800. }
  801. // cpu_idle - at the end of kern_init, the first kernel thread idleproc will do below works
  802. void
  803. cpu_idle(void) {
  804. while (1) {
  805. if (current->need_resched) {
  806. schedule();
  807. }
  808. }
  809. }
  810. //FOR LAB6, set the process's priority (bigger value will get more CPU time)
  811. void
  812. lab6_set_priority(uint32_t priority)
  813. {
  814. if (priority == 0)
  815. current->lab6_priority = 1;
  816. else current->lab6_priority = priority;
  817. }