process.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. #include "process.h"
  2. #include <common/printk.h>
  3. #include <common/kprint.h>
  4. #include <common/stdio.h>
  5. #include <common/compiler.h>
  6. #include <common/libELF/elf.h>
  7. #include <common/time.h>
  8. #include <driver/video/video.h>
  9. #include <driver/usb/usb.h>
  10. #include <exception/gate.h>
  11. #include <filesystem/fat32/fat32.h>
  12. #include <mm/slab.h>
  13. #include <process/spinlock.h>
  14. #include <syscall/syscall.h>
  15. #include <syscall/syscall_num.h>
  16. #include <sched/sched.h>
  17. #include <ktest/ktest.h>
  18. spinlock_t process_global_pid_write_lock; // 增加pid的写锁
  19. long process_global_pid = 1; // 系统中最大的pid
  20. extern void system_call(void);
  21. extern void kernel_thread_func(void);
  22. ul _stack_start; // initial proc的栈基地址(虚拟地址)
  23. struct mm_struct initial_mm = {0};
  24. struct thread_struct initial_thread =
  25. {
  26. .rbp = (ul)(initial_proc_union.stack + STACK_SIZE / sizeof(ul)),
  27. .rsp = (ul)(initial_proc_union.stack + STACK_SIZE / sizeof(ul)),
  28. .fs = KERNEL_DS,
  29. .gs = KERNEL_DS,
  30. .cr2 = 0,
  31. .trap_num = 0,
  32. .err_code = 0};
  33. // 初始化 初始进程的union ,并将其链接到.data.init_proc段内
  34. union proc_union initial_proc_union __attribute__((__section__(".data.init_proc_union"))) = {INITIAL_PROC(initial_proc_union.pcb)};
  35. struct process_control_block *initial_proc[MAX_CPU_NUM] = {&initial_proc_union.pcb, 0};
  36. // 为每个核心初始化初始进程的tss
  37. struct tss_struct initial_tss[MAX_CPU_NUM] = {[0 ... MAX_CPU_NUM - 1] = INITIAL_TSS};
  38. /**
  39. * @brief 拷贝当前进程的标志位
  40. *
  41. * @param clone_flags 克隆标志位
  42. * @param pcb 新的进程的pcb
  43. * @return uint64_t
  44. */
  45. uint64_t process_copy_flags(uint64_t clone_flags, struct process_control_block *pcb);
  46. /**
  47. * @brief 拷贝当前进程的文件描述符等信息
  48. *
  49. * @param clone_flags 克隆标志位
  50. * @param pcb 新的进程的pcb
  51. * @return uint64_t
  52. */
  53. uint64_t process_copy_files(uint64_t clone_flags, struct process_control_block *pcb);
  54. /**
  55. * @brief 回收进程的所有文件描述符
  56. *
  57. * @param pcb 要被回收的进程的pcb
  58. * @return uint64_t
  59. */
  60. uint64_t process_exit_files(struct process_control_block *pcb);
  61. /**
  62. * @brief 拷贝当前进程的内存空间分布结构体信息
  63. *
  64. * @param clone_flags 克隆标志位
  65. * @param pcb 新的进程的pcb
  66. * @return uint64_t
  67. */
  68. uint64_t process_copy_mm(uint64_t clone_flags, struct process_control_block *pcb);
  69. /**
  70. * @brief 释放进程的页表
  71. *
  72. * @param pcb 要被释放页表的进程
  73. * @return uint64_t
  74. */
  75. uint64_t process_exit_mm(struct process_control_block *pcb);
  76. /**
  77. * @brief 拷贝当前进程的线程结构体
  78. *
  79. * @param clone_flags 克隆标志位
  80. * @param pcb 新的进程的pcb
  81. * @return uint64_t
  82. */
  83. uint64_t process_copy_thread(uint64_t clone_flags, struct process_control_block *pcb, uint64_t stack_start, uint64_t stack_size, struct pt_regs *current_regs);
  84. void process_exit_thread(struct process_control_block *pcb);
  85. /**
  86. * @brief 切换进程
  87. *
  88. * @param prev 上一个进程的pcb
  89. * @param next 将要切换到的进程的pcb
  90. * 由于程序在进入内核的时候已经保存了寄存器,因此这里不需要保存寄存器。
  91. * 这里切换fs和gs寄存器
  92. */
  93. void __switch_to(struct process_control_block *prev, struct process_control_block *next)
  94. {
  95. initial_tss[proc_current_cpu_id].rsp0 = next->thread->rbp;
  96. // kdebug("next_rsp = %#018lx ", next->thread->rsp);
  97. // set_tss64((uint *)phys_2_virt(TSS64_Table), initial_tss[0].rsp0, initial_tss[0].rsp1, initial_tss[0].rsp2, initial_tss[0].ist1,
  98. // initial_tss[0].ist2, initial_tss[0].ist3, initial_tss[0].ist4, initial_tss[0].ist5, initial_tss[0].ist6, initial_tss[0].ist7);
  99. __asm__ __volatile__("movq %%fs, %0 \n\t"
  100. : "=a"(prev->thread->fs));
  101. __asm__ __volatile__("movq %%gs, %0 \n\t"
  102. : "=a"(prev->thread->gs));
  103. __asm__ __volatile__("movq %0, %%fs \n\t" ::"a"(next->thread->fs));
  104. __asm__ __volatile__("movq %0, %%gs \n\t" ::"a"(next->thread->gs));
  105. // wrmsr(0x175, next->thread->rbp);
  106. }
  107. /**
  108. * @brief 打开要执行的程序文件
  109. *
  110. * @param path
  111. * @return struct vfs_file_t*
  112. */
  113. struct vfs_file_t *process_open_exec_file(char *path)
  114. {
  115. struct vfs_dir_entry_t *dentry = NULL;
  116. struct vfs_file_t *filp = NULL;
  117. dentry = vfs_path_walk(path, 0);
  118. if (dentry == NULL)
  119. return (void *)-ENOENT;
  120. if (dentry->dir_inode->attribute == VFS_ATTR_DIR)
  121. return (void *)-ENOTDIR;
  122. filp = (struct vfs_file_t *)kmalloc(sizeof(struct vfs_file_t), 0);
  123. if (filp == NULL)
  124. return (void *)-ENOMEM;
  125. filp->position = 0;
  126. filp->mode = 0;
  127. filp->dEntry = dentry;
  128. filp->mode = ATTR_READ_ONLY;
  129. filp->file_ops = dentry->dir_inode->file_ops;
  130. return filp;
  131. }
  132. /**
  133. * @brief 加载elf格式的程序文件到内存中,并设置regs
  134. *
  135. * @param regs 寄存器
  136. * @param path 文件路径
  137. * @return int
  138. */
  139. static int process_load_elf_file(struct pt_regs *regs, char *path)
  140. {
  141. int retval = 0;
  142. struct vfs_file_t *filp = process_open_exec_file(path);
  143. if ((long)filp <= 0 && (long)filp >= -255)
  144. {
  145. // kdebug("(long)filp=%ld", (long)filp);
  146. return (unsigned long)filp;
  147. }
  148. void *buf = kmalloc(PAGE_4K_SIZE, 0);
  149. memset(buf, 0, PAGE_4K_SIZE);
  150. uint64_t pos = 0;
  151. pos = filp->file_ops->lseek(filp, 0, SEEK_SET);
  152. retval = filp->file_ops->read(filp, (char *)buf, sizeof(Elf64_Ehdr), &pos);
  153. retval = 0;
  154. if (!elf_check(buf))
  155. {
  156. kerror("Not an ELF file: %s", path);
  157. retval = -ENOTSUP;
  158. goto load_elf_failed;
  159. }
  160. #if ARCH(X86_64)
  161. // 暂时只支持64位的文件
  162. if (((Elf32_Ehdr *)buf)->e_ident[EI_CLASS] != ELFCLASS64)
  163. {
  164. kdebug("((Elf32_Ehdr *)buf)->e_ident[EI_CLASS]=%d", ((Elf32_Ehdr *)buf)->e_ident[EI_CLASS]);
  165. retval = -EUNSUPPORTED;
  166. goto load_elf_failed;
  167. }
  168. Elf64_Ehdr ehdr = *(Elf64_Ehdr *)buf;
  169. // 暂时只支持AMD64架构
  170. if (ehdr.e_machine != EM_AMD64)
  171. {
  172. kerror("e_machine=%d", ehdr.e_machine);
  173. retval = -EUNSUPPORTED;
  174. goto load_elf_failed;
  175. }
  176. #else
  177. #error Unsupported architecture!
  178. #endif
  179. if (ehdr.e_type != ET_EXEC)
  180. {
  181. kerror("Not executable file! filename=%s\tehdr->e_type=%d", path, ehdr.e_type);
  182. retval = -EUNSUPPORTED;
  183. goto load_elf_failed;
  184. }
  185. // kdebug("filename=%s:\te_entry=%#018lx", path, ehdr.e_entry);
  186. regs->rip = ehdr.e_entry;
  187. current_pcb->mm->code_addr_start = ehdr.e_entry;
  188. // kdebug("ehdr.e_phoff=%#018lx\t ehdr.e_phentsize=%d, ehdr.e_phnum=%d", ehdr.e_phoff, ehdr.e_phentsize, ehdr.e_phnum);
  189. // 将指针移动到program header处
  190. pos = ehdr.e_phoff;
  191. // 读取所有的phdr
  192. pos = filp->file_ops->lseek(filp, pos, SEEK_SET);
  193. filp->file_ops->read(filp, (char *)buf, (uint64_t)ehdr.e_phentsize * (uint64_t)ehdr.e_phnum, &pos);
  194. if ((unsigned long)filp <= 0)
  195. {
  196. kdebug("(unsigned long)filp=%d", (long)filp);
  197. retval = -ENOEXEC;
  198. goto load_elf_failed;
  199. }
  200. Elf64_Phdr *phdr = buf;
  201. // 将程序加载到内存中
  202. for (int i = 0; i < ehdr.e_phnum; ++i, ++phdr)
  203. {
  204. // kdebug("phdr[%d] phdr->p_offset=%#018lx phdr->p_vaddr=%#018lx phdr->p_memsz=%ld phdr->p_filesz=%ld phdr->p_type=%d", i, phdr->p_offset, phdr->p_vaddr, phdr->p_memsz, phdr->p_filesz, phdr->p_type);
  205. // 不是可加载的段
  206. if (phdr->p_type != PT_LOAD)
  207. continue;
  208. int64_t remain_mem_size = phdr->p_memsz;
  209. int64_t remain_file_size = phdr->p_filesz;
  210. pos = phdr->p_offset;
  211. uint64_t virt_base = phdr->p_vaddr;
  212. // kdebug("virt_base = %#018lx, &memory_management_struct=%#018lx", virt_base, &memory_management_struct);
  213. while (remain_mem_size > 0)
  214. {
  215. // todo: 改用slab分配4K大小内存块并映射到4K页
  216. if (!mm_check_mapped((uint64_t)current_pcb->mm->pgd, virt_base)) // 未映射,则新增物理页
  217. {
  218. mm_map_proc_page_table((uint64_t)current_pcb->mm->pgd, true, virt_base, alloc_pages(ZONE_NORMAL, 1, PAGE_PGT_MAPPED)->addr_phys, PAGE_2M_SIZE, PAGE_USER_PAGE, true, true, false);
  219. memset((void *)virt_base, 0, PAGE_2M_SIZE);
  220. }
  221. pos = filp->file_ops->lseek(filp, pos, SEEK_SET);
  222. int64_t val = 0;
  223. if (remain_file_size != 0)
  224. {
  225. int64_t to_trans = (remain_file_size > PAGE_2M_SIZE) ? PAGE_2M_SIZE : remain_file_size;
  226. val = filp->file_ops->read(filp, (char *)virt_base, to_trans, &pos);
  227. }
  228. if (val < 0)
  229. goto load_elf_failed;
  230. remain_mem_size -= PAGE_2M_SIZE;
  231. remain_file_size -= val;
  232. virt_base += PAGE_2M_SIZE;
  233. }
  234. }
  235. // 分配2MB的栈内存空间
  236. regs->rsp = current_pcb->mm->stack_start;
  237. regs->rbp = current_pcb->mm->stack_start;
  238. uint64_t pa = alloc_pages(ZONE_NORMAL, 1, PAGE_PGT_MAPPED)->addr_phys;
  239. mm_map_proc_page_table((uint64_t)current_pcb->mm->pgd, true, current_pcb->mm->stack_start - PAGE_2M_SIZE, pa, PAGE_2M_SIZE, PAGE_USER_PAGE, true, true, false);
  240. // 清空栈空间
  241. memset((void *)(current_pcb->mm->stack_start - PAGE_2M_SIZE), 0, PAGE_2M_SIZE);
  242. load_elf_failed:;
  243. if (buf != NULL)
  244. kfree(buf);
  245. return retval;
  246. }
  247. /**
  248. * @brief 使当前进程去执行新的代码
  249. *
  250. * @param regs 当前进程的寄存器
  251. * @param path 可执行程序的路径
  252. * @param argv 参数列表
  253. * @param envp 环境变量
  254. * @return ul 错误码
  255. */
  256. ul do_execve(struct pt_regs *regs, char *path, char *argv[], char *envp[])
  257. {
  258. // kdebug("do_execve is running...");
  259. // 当前进程正在与父进程共享地址空间,需要创建
  260. // 独立的地址空间才能使新程序正常运行
  261. if (current_pcb->flags & PF_VFORK)
  262. {
  263. kdebug("proc:%d creating new mem space", current_pcb->pid);
  264. // 分配新的内存空间分布结构体
  265. struct mm_struct *new_mms = (struct mm_struct *)kmalloc(sizeof(struct mm_struct), 0);
  266. memset(new_mms, 0, sizeof(struct mm_struct));
  267. current_pcb->mm = new_mms;
  268. // 分配顶层页表, 并设置顶层页表的物理地址
  269. new_mms->pgd = (pml4t_t *)virt_2_phys(kmalloc(PAGE_4K_SIZE, 0));
  270. // 由于高2K部分为内核空间,在接下来需要覆盖其数据,因此不用清零
  271. memset(phys_2_virt(new_mms->pgd), 0, PAGE_4K_SIZE / 2);
  272. // 拷贝内核空间的页表指针
  273. memcpy(phys_2_virt(new_mms->pgd) + 256, phys_2_virt(initial_proc[proc_current_cpu_id]) + 256, PAGE_4K_SIZE / 2);
  274. }
  275. // 设置用户栈和用户堆的基地址
  276. unsigned long stack_start_addr = 0x6ffff0a00000UL;
  277. const uint64_t brk_start_addr = 0x700000000000UL;
  278. process_switch_mm(current_pcb);
  279. // 为用户态程序设置地址边界
  280. if (!(current_pcb->flags & PF_KTHREAD))
  281. current_pcb->addr_limit = USER_MAX_LINEAR_ADDR;
  282. current_pcb->mm->code_addr_end = 0;
  283. current_pcb->mm->data_addr_start = 0;
  284. current_pcb->mm->data_addr_end = 0;
  285. current_pcb->mm->rodata_addr_start = 0;
  286. current_pcb->mm->rodata_addr_end = 0;
  287. current_pcb->mm->bss_start = 0;
  288. current_pcb->mm->bss_end = 0;
  289. current_pcb->mm->brk_start = brk_start_addr;
  290. current_pcb->mm->brk_end = brk_start_addr;
  291. current_pcb->mm->stack_start = stack_start_addr;
  292. // 关闭之前的文件描述符
  293. process_exit_files(current_pcb);
  294. // 清除进程的vfork标志位
  295. current_pcb->flags &= ~PF_VFORK;
  296. // 加载elf格式的可执行文件
  297. int tmp = process_load_elf_file(regs, path);
  298. if (tmp < 0)
  299. goto exec_failed;
  300. // 拷贝参数列表
  301. if (argv != NULL)
  302. {
  303. int argc = 0;
  304. // 目标程序的argv基地址指针,最大8个参数
  305. char **dst_argv = (char **)(stack_start_addr - (sizeof(char **) << 3));
  306. uint64_t str_addr = (uint64_t)dst_argv;
  307. for (argc = 0; argc < 8 && argv[argc] != NULL; ++argc)
  308. {
  309. if (*argv[argc] == NULL)
  310. break;
  311. // 测量参数的长度(最大1023)
  312. int argv_len = strnlen_user(argv[argc], 1023) + 1;
  313. strncpy((char *)(str_addr - argv_len), argv[argc], argv_len - 1);
  314. str_addr -= argv_len;
  315. dst_argv[argc] = (char *)str_addr;
  316. //字符串加上结尾字符
  317. ((char *)str_addr)[argv_len] = '\0';
  318. }
  319. // 重新设定栈基址,并预留空间防止越界
  320. stack_start_addr = str_addr - 8;
  321. current_pcb->mm->stack_start = stack_start_addr;
  322. regs->rsp = regs->rbp = stack_start_addr;
  323. // 传递参数
  324. regs->rdi = argc;
  325. regs->rsi = (uint64_t)dst_argv;
  326. }
  327. // kdebug("execve ok");
  328. regs->cs = USER_CS | 3;
  329. regs->ds = USER_DS | 3;
  330. regs->ss = USER_DS | 0x3;
  331. regs->rflags = 0x200246;
  332. regs->rax = 1;
  333. regs->es = 0;
  334. return 0;
  335. exec_failed:;
  336. process_do_exit(tmp);
  337. }
  338. /**
  339. * @brief 内核init进程
  340. *
  341. * @param arg
  342. * @return ul 参数
  343. */
  344. ul initial_kernel_thread(ul arg)
  345. {
  346. // kinfo("initial proc running...\targ:%#018lx", arg);
  347. fat32_init();
  348. usb_init();
  349. // 对一些组件进行单元测试
  350. ktest_start(ktest_test_bitree, 0);
  351. ktest_start(ktest_test_kfifo, 0);
  352. // 准备切换到用户态
  353. struct pt_regs *regs;
  354. current_pcb->thread->rip = (ul)ret_from_system_call;
  355. current_pcb->thread->rsp = (ul)current_pcb + STACK_SIZE - sizeof(struct pt_regs);
  356. current_pcb->thread->fs = USER_DS | 0x3;
  357. current_pcb->thread->gs = USER_DS | 0x3;
  358. // 主动放弃内核线程身份
  359. current_pcb->flags &= (~PF_KTHREAD);
  360. kdebug("in initial_kernel_thread: flags=%ld", current_pcb->flags);
  361. // current_pcb->mm->pgd = kmalloc(PAGE_4K_SIZE, 0);
  362. // memset((void*)current_pcb->mm->pgd, 0, PAGE_4K_SIZE);
  363. regs = (struct pt_regs *)current_pcb->thread->rsp;
  364. // kdebug("current_pcb->thread->rsp=%#018lx", current_pcb->thread->rsp);
  365. current_pcb->flags = 0;
  366. // 将返回用户层的代码压入堆栈,向rdx传入regs的地址,然后jmp到do_execve这个系统调用api的处理函数 这里的设计思路和switch_proc类似
  367. // 加载用户态程序:shell.elf
  368. char init_path[] = "/shell.elf";
  369. uint64_t addr = (uint64_t)&init_path;
  370. __asm__ __volatile__("movq %1, %%rsp \n\t"
  371. "pushq %2 \n\t"
  372. "jmp do_execve \n\t" ::"D"(current_pcb->thread->rsp),
  373. "m"(current_pcb->thread->rsp), "m"(current_pcb->thread->rip), "S"("/shell.elf"), "c"(NULL), "d"(NULL)
  374. : "memory");
  375. return 1;
  376. }
  377. /**
  378. * @brief 当子进程退出后向父进程发送通知
  379. *
  380. */
  381. void process_exit_notify()
  382. {
  383. wait_queue_wakeup(&current_pcb->parent_pcb->wait_child_proc_exit, PROC_INTERRUPTIBLE);
  384. }
  385. /**
  386. * @brief 进程退出时执行的函数
  387. *
  388. * @param code 返回码
  389. * @return ul
  390. */
  391. ul process_do_exit(ul code)
  392. {
  393. // kinfo("process exiting..., code is %ld.", (long)code);
  394. cli();
  395. struct process_control_block *pcb = current_pcb;
  396. // 进程退出时释放资源
  397. process_exit_files(pcb);
  398. process_exit_thread(pcb);
  399. // todo: 可否在这里释放内存结构体?(在判断共享页引用问题之后)
  400. pcb->state = PROC_ZOMBIE;
  401. pcb->exit_code = code;
  402. sti();
  403. process_exit_notify();
  404. sched_cfs();
  405. while (1)
  406. hlt();
  407. }
  408. /**
  409. * @brief 初始化内核进程
  410. *
  411. * @param fn 目标程序的地址
  412. * @param arg 向目标程序传入的参数
  413. * @param flags
  414. * @return int
  415. */
  416. int kernel_thread(unsigned long (*fn)(unsigned long), unsigned long arg, unsigned long flags)
  417. {
  418. struct pt_regs regs;
  419. memset(&regs, 0, sizeof(regs));
  420. // 在rbx寄存器中保存进程的入口地址
  421. regs.rbx = (ul)fn;
  422. // 在rdx寄存器中保存传入的参数
  423. regs.rdx = (ul)arg;
  424. regs.ds = KERNEL_DS;
  425. regs.es = KERNEL_DS;
  426. regs.cs = KERNEL_CS;
  427. regs.ss = KERNEL_DS;
  428. // 置位中断使能标志位
  429. regs.rflags = (1 << 9);
  430. // rip寄存器指向内核线程的引导程序
  431. regs.rip = (ul)kernel_thread_func;
  432. // kdebug("kernel_thread_func=%#018lx", kernel_thread_func);
  433. // kdebug("&kernel_thread_func=%#018lx", &kernel_thread_func);
  434. // kdebug("1111\tregs.rip = %#018lx", regs.rip);
  435. return do_fork(&regs, flags | CLONE_VM, 0, 0);
  436. }
  437. /**
  438. * @brief 初始化进程模块
  439. * ☆前置条件:已完成系统调用模块的初始化
  440. */
  441. void process_init()
  442. {
  443. kinfo("Initializing process...");
  444. initial_mm.pgd = (pml4t_t *)get_CR3();
  445. initial_mm.code_addr_start = memory_management_struct.kernel_code_start;
  446. initial_mm.code_addr_end = memory_management_struct.kernel_code_end;
  447. initial_mm.data_addr_start = (ul)&_data;
  448. initial_mm.data_addr_end = memory_management_struct.kernel_data_end;
  449. initial_mm.rodata_addr_start = (ul)&_rodata;
  450. initial_mm.rodata_addr_end = (ul)&_erodata;
  451. initial_mm.bss_start = (uint64_t)&_bss;
  452. initial_mm.bss_end = (uint64_t)&_ebss;
  453. initial_mm.brk_start = memory_management_struct.start_brk;
  454. initial_mm.brk_end = current_pcb->addr_limit;
  455. initial_mm.stack_start = _stack_start;
  456. initial_tss[proc_current_cpu_id].rsp0 = initial_thread.rbp;
  457. // ========= 在IDLE进程的顶层页表中添加对内核地址空间的映射 =====================
  458. // 由于IDLE进程的顶层页表的高地址部分会被后续进程所复制,为了使所有进程能够共享相同的内核空间,
  459. // 因此需要先在IDLE进程的顶层页表内映射二级页表
  460. uint64_t *idle_pml4t_vaddr = (uint64_t *)phys_2_virt((uint64_t)get_CR3() & (~0xfffUL));
  461. for (int i = 256; i < 512; ++i)
  462. {
  463. uint64_t *tmp = idle_pml4t_vaddr + i;
  464. if (*tmp == 0)
  465. {
  466. void *pdpt = kmalloc(PAGE_4K_SIZE, 0);
  467. memset(pdpt, 0, PAGE_4K_SIZE);
  468. set_pml4t(tmp, mk_pml4t(virt_2_phys(pdpt), PAGE_KERNEL_PGT));
  469. }
  470. }
  471. /*
  472. kdebug("initial_thread.rbp=%#018lx", initial_thread.rbp);
  473. kdebug("initial_tss[0].rsp1=%#018lx", initial_tss[0].rsp1);
  474. kdebug("initial_tss[0].ist1=%#018lx", initial_tss[0].ist1);
  475. */
  476. // 初始化pid的写锁
  477. spin_init(&process_global_pid_write_lock);
  478. // 初始化进程的循环链表
  479. list_init(&initial_proc_union.pcb.list);
  480. kernel_thread(initial_kernel_thread, 10, CLONE_FS | CLONE_SIGNAL); // 初始化内核线程
  481. initial_proc_union.pcb.state = PROC_RUNNING;
  482. initial_proc_union.pcb.preempt_count = 0;
  483. initial_proc_union.pcb.cpu_id = 0;
  484. initial_proc_union.pcb.virtual_runtime = (1UL << 60);
  485. current_pcb->virtual_runtime = (1UL << 60);
  486. }
  487. /**
  488. * @brief fork当前进程
  489. *
  490. * @param regs 新的寄存器值
  491. * @param clone_flags 克隆标志
  492. * @param stack_start 堆栈开始地址
  493. * @param stack_size 堆栈大小
  494. * @return unsigned long
  495. */
  496. unsigned long do_fork(struct pt_regs *regs, unsigned long clone_flags, unsigned long stack_start, unsigned long stack_size)
  497. {
  498. int retval = 0;
  499. struct process_control_block *tsk = NULL;
  500. // kdebug("222\tregs.rip = %#018lx", regs->rip);
  501. // 为新的进程分配栈空间,并将pcb放置在底部
  502. tsk = (struct process_control_block *)kmalloc(STACK_SIZE, 0);
  503. // kdebug("struct process_control_block ADDRESS=%#018lx", (uint64_t)tsk);
  504. if (tsk == NULL)
  505. {
  506. retval = -ENOMEM;
  507. return retval;
  508. }
  509. memset(tsk, 0, sizeof(struct process_control_block));
  510. // 将当前进程的pcb复制到新的pcb内
  511. memcpy(tsk, current_pcb, sizeof(struct process_control_block));
  512. // kdebug("current_pcb->flags=%#010lx", current_pcb->flags);
  513. // 将进程加入循环链表
  514. list_init(&tsk->list);
  515. // list_add(&initial_proc_union.pcb.list, &tsk->list);
  516. tsk->priority = 2;
  517. tsk->preempt_count = 0;
  518. // 增加全局的pid并赋值给新进程的pid
  519. spin_lock(&process_global_pid_write_lock);
  520. tsk->pid = process_global_pid++;
  521. // 加入到进程链表中
  522. tsk->next_pcb = initial_proc_union.pcb.next_pcb;
  523. initial_proc_union.pcb.next_pcb = tsk;
  524. tsk->parent_pcb = current_pcb;
  525. spin_unlock(&process_global_pid_write_lock);
  526. tsk->cpu_id = proc_current_cpu_id;
  527. tsk->state = PROC_UNINTERRUPTIBLE;
  528. tsk->parent_pcb = current_pcb;
  529. wait_queue_init(&tsk->wait_child_proc_exit, NULL);
  530. list_init(&tsk->list);
  531. // list_add(&initial_proc_union.pcb.list, &tsk->list);
  532. retval = -ENOMEM;
  533. // 拷贝标志位
  534. if (process_copy_flags(clone_flags, tsk))
  535. goto copy_flags_failed;
  536. // 拷贝内存空间分布结构体
  537. if (process_copy_mm(clone_flags, tsk))
  538. goto copy_mm_failed;
  539. // 拷贝文件
  540. if (process_copy_files(clone_flags, tsk))
  541. goto copy_files_failed;
  542. // 拷贝线程结构体
  543. if (process_copy_thread(clone_flags, tsk, stack_start, stack_size, regs))
  544. goto copy_thread_failed;
  545. // 拷贝成功
  546. retval = tsk->pid;
  547. // 唤醒进程
  548. process_wakeup(tsk);
  549. return retval;
  550. copy_thread_failed:;
  551. // 回收线程
  552. process_exit_thread(tsk);
  553. copy_files_failed:;
  554. // 回收文件
  555. process_exit_files(tsk);
  556. copy_mm_failed:;
  557. // 回收内存空间分布结构体
  558. process_exit_mm(tsk);
  559. copy_flags_failed:;
  560. kfree(tsk);
  561. return retval;
  562. return 0;
  563. }
  564. /**
  565. * @brief 根据pid获取进程的pcb
  566. *
  567. * @param pid
  568. * @return struct process_control_block*
  569. */
  570. struct process_control_block *process_get_pcb(long pid)
  571. {
  572. struct process_control_block *pcb = initial_proc_union.pcb.next_pcb;
  573. // 使用蛮力法搜索指定pid的pcb
  574. // todo: 使用哈希表来管理pcb
  575. for (; pcb != &initial_proc_union.pcb; pcb = pcb->next_pcb)
  576. {
  577. if (pcb->pid == pid)
  578. return pcb;
  579. }
  580. return NULL;
  581. }
  582. /**
  583. * @brief 将进程加入到调度器的就绪队列中
  584. *
  585. * @param pcb 进程的pcb
  586. */
  587. void process_wakeup(struct process_control_block *pcb)
  588. {
  589. pcb->state = PROC_RUNNING;
  590. sched_cfs_enqueue(pcb);
  591. }
  592. /**
  593. * @brief 将进程加入到调度器的就绪队列中,并标志当前进程需要被调度
  594. *
  595. * @param pcb 进程的pcb
  596. */
  597. void process_wakeup_immediately(struct process_control_block *pcb)
  598. {
  599. pcb->state = PROC_RUNNING;
  600. sched_cfs_enqueue(pcb);
  601. // 将当前进程标志为需要调度,缩短新进程被wakeup的时间
  602. current_pcb->flags |= PF_NEED_SCHED;
  603. }
  604. /**
  605. * @brief 拷贝当前进程的标志位
  606. *
  607. * @param clone_flags 克隆标志位
  608. * @param pcb 新的进程的pcb
  609. * @return uint64_t
  610. */
  611. uint64_t process_copy_flags(uint64_t clone_flags, struct process_control_block *pcb)
  612. {
  613. if (clone_flags & CLONE_VM)
  614. pcb->flags |= PF_VFORK;
  615. return 0;
  616. }
  617. /**
  618. * @brief 拷贝当前进程的文件描述符等信息
  619. *
  620. * @param clone_flags 克隆标志位
  621. * @param pcb 新的进程的pcb
  622. * @return uint64_t
  623. */
  624. uint64_t process_copy_files(uint64_t clone_flags, struct process_control_block *pcb)
  625. {
  626. int retval = 0;
  627. // 如果CLONE_FS被置位,那么子进程与父进程共享文件描述符
  628. // 文件描述符已经在复制pcb时被拷贝
  629. if (clone_flags & CLONE_FS)
  630. return retval;
  631. // 为新进程拷贝新的文件描述符
  632. for (int i = 0; i < PROC_MAX_FD_NUM; ++i)
  633. {
  634. if (current_pcb->fds[i] == NULL)
  635. continue;
  636. pcb->fds[i] = (struct vfs_file_t *)kmalloc(sizeof(struct vfs_file_t), 0);
  637. memcpy(pcb->fds[i], current_pcb->fds[i], sizeof(struct vfs_file_t));
  638. }
  639. return retval;
  640. }
  641. /**
  642. * @brief 回收进程的所有文件描述符
  643. *
  644. * @param pcb 要被回收的进程的pcb
  645. * @return uint64_t
  646. */
  647. uint64_t process_exit_files(struct process_control_block *pcb)
  648. {
  649. // 不与父进程共享文件描述符
  650. if (!(pcb->flags & PF_VFORK))
  651. {
  652. for (int i = 0; i < PROC_MAX_FD_NUM; ++i)
  653. {
  654. if (pcb->fds[i] == NULL)
  655. continue;
  656. kfree(pcb->fds[i]);
  657. }
  658. }
  659. // 清空当前进程的文件描述符列表
  660. memset(pcb->fds, 0, sizeof(struct vfs_file_t *) * PROC_MAX_FD_NUM);
  661. }
  662. /**
  663. * @brief 拷贝当前进程的内存空间分布结构体信息
  664. *
  665. * @param clone_flags 克隆标志位
  666. * @param pcb 新的进程的pcb
  667. * @return uint64_t
  668. */
  669. uint64_t process_copy_mm(uint64_t clone_flags, struct process_control_block *pcb)
  670. {
  671. int retval = 0;
  672. // 与父进程共享内存空间
  673. if (clone_flags & CLONE_VM)
  674. {
  675. // kdebug("copy_vm\t current_pcb->mm->pgd=%#018lx", current_pcb->mm->pgd);
  676. pcb->mm = current_pcb->mm;
  677. return retval;
  678. }
  679. // 分配新的内存空间分布结构体
  680. struct mm_struct *new_mms = (struct mm_struct *)kmalloc(sizeof(struct mm_struct), 0);
  681. memset(new_mms, 0, sizeof(struct mm_struct));
  682. memcpy(new_mms, current_pcb->mm, sizeof(struct mm_struct));
  683. pcb->mm = new_mms;
  684. // 分配顶层页表, 并设置顶层页表的物理地址
  685. new_mms->pgd = (pml4t_t *)virt_2_phys(kmalloc(PAGE_4K_SIZE, 0));
  686. // 由于高2K部分为内核空间,在接下来需要覆盖其数据,因此不用清零
  687. memset(phys_2_virt(new_mms->pgd), 0, PAGE_4K_SIZE / 2);
  688. // 拷贝内核空间的页表指针
  689. memcpy(phys_2_virt(new_mms->pgd) + 256, phys_2_virt(initial_proc[proc_current_cpu_id]->mm->pgd) + 256, PAGE_4K_SIZE / 2);
  690. uint64_t *current_pgd = (uint64_t *)phys_2_virt(current_pcb->mm->pgd);
  691. uint64_t *new_pml4t = (uint64_t *)phys_2_virt(new_mms->pgd);
  692. // 迭代地拷贝用户空间
  693. for (int i = 0; i <= 255; ++i)
  694. {
  695. // 当前页表项为空
  696. if ((*(uint64_t *)(current_pgd + i)) == 0)
  697. continue;
  698. // 分配新的二级页表
  699. uint64_t *new_pdpt = (uint64_t *)kmalloc(PAGE_4K_SIZE, 0);
  700. memset(new_pdpt, 0, PAGE_4K_SIZE);
  701. // 在新的一级页表中设置新的二级页表表项
  702. set_pml4t(new_pml4t + i, mk_pml4t(virt_2_phys(new_pdpt), (*(current_pgd + i)) & 0xfffUL));
  703. uint64_t *current_pdpt = (uint64_t *)phys_2_virt((*(uint64_t *)(current_pgd + i)) & (~0xfffUL));
  704. // kdebug("current_pdpt=%#018lx, current_pid=%d", current_pdpt, current_pcb->pid);
  705. for (int j = 0; j < 512; ++j)
  706. {
  707. if (*(current_pdpt + j) == 0)
  708. continue;
  709. // 分配新的三级页表
  710. uint64_t *new_pdt = (uint64_t *)kmalloc(PAGE_4K_SIZE, 0);
  711. memset(new_pdt, 0, PAGE_4K_SIZE);
  712. // 在二级页表中填写新的三级页表
  713. // 在新的二级页表中设置三级页表的表项
  714. set_pdpt((uint64_t *)(new_pdpt + j), mk_pdpt(virt_2_phys(new_pdt), (*(current_pdpt + j)) & 0xfffUL));
  715. uint64_t *current_pdt = (uint64_t *)phys_2_virt((*(current_pdpt + j)) & (~0xfffUL));
  716. // kdebug("current_pdt=%#018lx", current_pdt);
  717. // 循环拷贝三级页表
  718. for (int k = 0; k < 512; ++k)
  719. {
  720. if (*(current_pdt + k) == 0)
  721. continue;
  722. // 获取新的物理页
  723. uint64_t pa = alloc_pages(ZONE_NORMAL, 1, PAGE_PGT_MAPPED)->addr_phys;
  724. memset((void *)phys_2_virt(pa), 0, PAGE_2M_SIZE);
  725. set_pdt((uint64_t *)(new_pdt + k), mk_pdt(pa, *(current_pdt + k) & 0x1ffUL));
  726. // 拷贝数据
  727. memcpy(phys_2_virt(pa), phys_2_virt((*(current_pdt + k)) & (~0x1ffUL)), PAGE_2M_SIZE);
  728. }
  729. }
  730. }
  731. return retval;
  732. }
  733. /**
  734. * @brief 释放进程的页表
  735. *
  736. * @param pcb 要被释放页表的进程
  737. * @return uint64_t
  738. */
  739. uint64_t process_exit_mm(struct process_control_block *pcb)
  740. {
  741. if (pcb->flags & CLONE_VM)
  742. return 0;
  743. if (pcb->mm == NULL)
  744. {
  745. kdebug("pcb->mm==NULL");
  746. return 0;
  747. }
  748. if (pcb->mm->pgd == NULL)
  749. {
  750. kdebug("pcb->mm->pgd==NULL");
  751. return 0;
  752. }
  753. // 获取顶层页表
  754. pml4t_t *current_pgd = (pml4t_t *)phys_2_virt(pcb->mm->pgd);
  755. // 迭代地释放用户空间
  756. for (int i = 0; i <= 255; ++i)
  757. {
  758. // 当前页表项为空
  759. if ((current_pgd + i)->pml4t == 0)
  760. continue;
  761. // 二级页表entry
  762. pdpt_t *current_pdpt = (pdpt_t *)phys_2_virt((current_pgd + i)->pml4t & (~0xfffUL));
  763. // 遍历二级页表
  764. for (int j = 0; j < 512; ++j)
  765. {
  766. if ((current_pdpt + j)->pdpt == 0)
  767. continue;
  768. // 三级页表的entry
  769. pdt_t *current_pdt = (pdt_t *)phys_2_virt((current_pdpt + j)->pdpt & (~0xfffUL));
  770. // 释放三级页表的内存页
  771. for (int k = 0; k < 512; ++k)
  772. {
  773. if ((current_pdt + k)->pdt == 0)
  774. continue;
  775. // 存在4级页表
  776. if (unlikely(((current_pdt + k)->pdt & (1 << 7)) == 0))
  777. {
  778. // 存在4K页
  779. uint64_t *pt_ptr = (uint64_t *)phys_2_virt((current_pdt + k)->pdt & (~0x1fffUL));
  780. uint64_t *pte_ptr = pt_ptr;
  781. // 循环处理4K页表, 直接清空
  782. // todo: 当支持使用slab分配4K内存作为进程的4K页之后,在这里需要释放这些4K对象
  783. for (int16_t g = 0; g < 512; ++g, ++pte_ptr)
  784. *pte_ptr = 0;
  785. // 4级页表已经空了,释放页表
  786. if (unlikely(mm_check_page_table(pt_ptr)) == 0)
  787. kfree(pt_ptr);
  788. }
  789. else
  790. {
  791. // 释放内存页
  792. if (mm_is_2M_page((current_pdt + k)->pdt & (~0x1fffUL))) // 校验是否为内存中的物理页
  793. free_pages(Phy_to_2M_Page((current_pdt + k)->pdt & (~0x1fffUL)), 1);
  794. }
  795. }
  796. // 释放三级页表
  797. kfree(current_pdt);
  798. }
  799. // 释放二级页表
  800. kfree(current_pdpt);
  801. }
  802. // 释放顶层页表
  803. kfree(current_pgd);
  804. // 释放内存空间分布结构体
  805. kfree(pcb->mm);
  806. return 0;
  807. }
  808. /**
  809. * @brief 拷贝当前进程的线程结构体
  810. *
  811. * @param clone_flags 克隆标志位
  812. * @param pcb 新的进程的pcb
  813. * @return uint64_t
  814. */
  815. uint64_t process_copy_thread(uint64_t clone_flags, struct process_control_block *pcb, uint64_t stack_start, uint64_t stack_size, struct pt_regs *current_regs)
  816. {
  817. // 将线程结构体放置在pcb后方
  818. struct thread_struct *thd = (struct thread_struct *)(pcb + 1);
  819. memset(thd, 0, sizeof(struct thread_struct));
  820. pcb->thread = thd;
  821. // 拷贝栈空间
  822. struct pt_regs *child_regs = (struct pt_regs *)((uint64_t)pcb + STACK_SIZE - sizeof(struct pt_regs));
  823. memcpy(child_regs, current_regs, sizeof(struct pt_regs));
  824. // 设置子进程的返回值为0
  825. child_regs->rax = 0;
  826. child_regs->rsp = stack_start;
  827. thd->rbp = (uint64_t)pcb + STACK_SIZE;
  828. thd->rsp = (uint64_t)child_regs;
  829. thd->fs = current_pcb->thread->fs;
  830. thd->gs = current_pcb->thread->gs;
  831. // kdebug("pcb->flags=%ld", pcb->flags);
  832. // 根据是否为内核线程,设置进程的开始执行的地址
  833. if (pcb->flags & PF_KTHREAD)
  834. thd->rip = (uint64_t)kernel_thread_func;
  835. else
  836. thd->rip = (uint64_t)ret_from_system_call;
  837. // kdebug("new proc's ret addr = %#018lx\tthd->rip=%#018lx stack_start=%#018lx child_regs->rsp = %#018lx, new_rip=%#018lx)", child_regs->rbx, thd->rip, stack_start, child_regs->rsp, child_regs->rip);
  838. return 0;
  839. }
  840. /**
  841. * @brief todo: 回收线程结构体
  842. *
  843. * @param pcb
  844. */
  845. void process_exit_thread(struct process_control_block *pcb)
  846. {
  847. }