process.c 31 KB

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