process.c 28 KB

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