process.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /* Process management: create, exit, round-robin schedule, ps, kill. */
  2. #include "process.h"
  3. #include "elf.h"
  4. #include "idle.h"
  5. #include "io.h"
  6. #include "kmalloc.h"
  7. #include "mm.h"
  8. #include "paging.h"
  9. #include "serial.h"
  10. #include "sys_fs.h"
  11. #include "sys_net.h"
  12. #include "timer.h"
  13. struct process *procs; /* dynamically-sized process table */
  14. volatile unsigned int current_pid;
  15. static unsigned int proc_cap; /* current capacity of procs[] */
  16. static unsigned int next_pid_counter = 1; /* monotonic, wraps */
  17. static unsigned int fallback_stack_next; /* 0..PROC_FALLBACK_STACK_MAX */
  18. /* Top of the in-image bootstrap stack (see kernel.ld). */
  19. extern char __boot_stack_top[];
  20. #define INITIAL_PROC_CAP 16
  21. /* ---- interrupt flag save/restore (for short critical sections) ---- */
  22. static inline unsigned int irq_save_disable(void)
  23. {
  24. unsigned int flags;
  25. __asm__ volatile ("pushfl; popl %0; cli" : "=r"(flags));
  26. return flags;
  27. }
  28. static inline void irq_restore(unsigned int flags)
  29. {
  30. __asm__ volatile ("pushl %0; popfl" : : "r"(flags));
  31. }
  32. /* Fallback pool: a static array, so its address is not a fixed memory-map
  33. * entry (same reasoning as the in-image stack in kernel.ld). */
  34. static unsigned int fallback_stacks[PROC_FALLBACK_STACK_MAX][PROC_STACK_SIZE / 4]
  35. __attribute__((aligned(16)));
  36. /* Allocate a process stack and return its BASE address (page-aligned), or 0.
  37. * *owned is set to 1 if it came from the frame allocator (must be freed on
  38. * exit), 0 if it came from the fallback pool. */
  39. static unsigned int stack_alloc(int *owned)
  40. {
  41. unsigned int base = mm_alloc_page();
  42. if (base) {
  43. *owned = 1;
  44. return base;
  45. }
  46. if (fallback_stack_next < PROC_FALLBACK_STACK_MAX) {
  47. base = (unsigned int)&fallback_stacks[fallback_stack_next][0];
  48. fallback_stack_next++;
  49. *owned = 0;
  50. return base;
  51. }
  52. return 0;
  53. }
  54. /* Clear one control block. kmalloc memory is not zeroed and QEMU hides that
  55. * (guest RAM starts cleared), so a fresh slot would otherwise carry garbage in
  56. * cr3/pid/state; schedule() and process_map_mmio_all() trust those fields and
  57. * a garbage cr3 made the boot-time MMIO mapping fault on real hardware. */
  58. static void clear_proc(struct process *p)
  59. {
  60. unsigned char *b = (unsigned char *)p;
  61. unsigned int i;
  62. for (i = 0; i < sizeof(*p); i++)
  63. b[i] = 0;
  64. }
  65. static void name_copy(char *dst, const char *src)
  66. {
  67. unsigned int i;
  68. for (i = 0; i < PROC_NAME_LEN - 1 && src[i]; i++)
  69. dst[i] = src[i];
  70. dst[i] = '\0';
  71. }
  72. /* Double the process table. Called with interrupts disabled. */
  73. static int grow_proc_table(void)
  74. {
  75. unsigned int new_cap = proc_cap * 2;
  76. struct process *np =
  77. (struct process *)kmalloc(new_cap * sizeof(struct process));
  78. unsigned int i;
  79. if (!np)
  80. return 0;
  81. for (i = 0; i < proc_cap; i++)
  82. np[i] = procs[i];
  83. for (i = proc_cap; i < new_cap; i++)
  84. clear_proc(&np[i]);
  85. kfree(procs);
  86. procs = np;
  87. proc_cap = new_cap;
  88. return 1;
  89. }
  90. /* Find a free process slot (1..proc_cap-1), growing the table if needed.
  91. * Slot 0 is the window manager and is never returned. Called with interrupts
  92. * disabled. Returns the slot index, or -1 on failure. */
  93. static int alloc_slot(void)
  94. {
  95. unsigned int slot;
  96. for (slot = 1; slot < proc_cap; slot++)
  97. if (procs[slot].state == PROC_UNUSED)
  98. return (int)slot;
  99. if (!grow_proc_table())
  100. return -1;
  101. for (slot = 1; slot < proc_cap; slot++)
  102. if (procs[slot].state == PROC_UNUSED)
  103. return (int)slot;
  104. return -1;
  105. }
  106. void process_init(void)
  107. {
  108. unsigned int i;
  109. procs = (struct process *)kmalloc(INITIAL_PROC_CAP * sizeof(struct process));
  110. if (!procs) {
  111. serial_puts(SERIAL_COM1, "process_init: out of memory\n");
  112. for (;;)
  113. __asm__ volatile ("cli; hlt");
  114. }
  115. proc_cap = INITIAL_PROC_CAP;
  116. for (i = 0; i < proc_cap; i++)
  117. clear_proc(&procs[i]);
  118. procs[0].state = PROC_RUNNING;
  119. procs[0].pid = 0;
  120. procs[0].esp = 0;
  121. procs[0].screen = (void *)0;
  122. procs[0].stack_base = 0; /* bootstrap stack, never freed */
  123. procs[0].cr3 = paging_current_cr3();
  124. procs[0].kstack_top = (unsigned int)__boot_stack_top;
  125. name_copy(procs[0].name, "wm");
  126. current_pid = 0;
  127. }
  128. /*
  129. * Build initial stack frame for a new process so that popa + iret
  130. * "returns" to the entry point. For arg-taking entries the argument
  131. * string is copied onto the stack and a pointer to it passed as the
  132. * first C parameter.
  133. *
  134. * Stack layout (high to low):
  135. *
  136. * [copied arg string, if any, rounded up to 4-byte boundary]
  137. * arg pointer -- first C parameter (only if has_arg)
  138. * process_exit address -- return address seen by the entry function
  139. * EFLAGS (0x202) -- IF=1
  140. * CS (0x08)
  141. * EIP (entry) -- iret target
  142. * EAX ECX EDX EBX ESP_orig EBP ESI EDI (pusha frame)
  143. * <- saved ESP
  144. */
  145. static int setup_process(const char *name, unsigned int entry,
  146. int has_arg, const char *arg)
  147. {
  148. int slot, owned;
  149. unsigned int base, top, *sp, arg_ptr = 0, cr3;
  150. unsigned int flags;
  151. flags = irq_save_disable();
  152. slot = alloc_slot();
  153. if (slot < 0) {
  154. irq_restore(flags);
  155. return -1;
  156. }
  157. cr3 = paging_new_directory();
  158. if (!cr3) {
  159. irq_restore(flags);
  160. return -1;
  161. }
  162. base = stack_alloc(&owned);
  163. if (!base) {
  164. mm_free_page(cr3);
  165. irq_restore(flags);
  166. return -1;
  167. }
  168. top = base + PROC_STACK_SIZE;
  169. sp = (unsigned int *)top;
  170. if (has_arg && arg) {
  171. unsigned int len, aligned, i;
  172. char *dst;
  173. for (len = 0; arg[len]; len++)
  174. ;
  175. len++;
  176. aligned = (len + 3) & ~3u;
  177. sp = (unsigned int *)((unsigned int)sp - aligned);
  178. dst = (char *)sp;
  179. for (i = 0; i < len; i++)
  180. dst[i] = arg[i];
  181. for (; i < aligned; i++)
  182. dst[i] = '\0';
  183. arg_ptr = (unsigned int)sp;
  184. }
  185. if (has_arg)
  186. *--sp = arg_ptr;
  187. *--sp = (unsigned int)process_exit;
  188. *--sp = 0x202; /* EFLAGS: IF=1 */
  189. *--sp = 0x08; /* CS */
  190. *--sp = entry; /* EIP */
  191. *--sp = 0; /* EAX */
  192. *--sp = 0; /* ECX */
  193. *--sp = 0; /* EDX */
  194. *--sp = 0; /* EBX */
  195. *--sp = 0; /* ESP (ignored by popa) */
  196. *--sp = 0; /* EBP */
  197. *--sp = 0; /* ESI */
  198. *--sp = 0; /* EDI */
  199. procs[slot].esp = (unsigned int)sp;
  200. procs[slot].state = PROC_READY;
  201. procs[slot].pid = next_pid_counter++;
  202. procs[slot].stack_base = owned ? base : 0;
  203. procs[slot].cr3 = cr3;
  204. procs[slot].kstack_top = top;
  205. name_copy(procs[slot].name, name);
  206. /* Child inherits the parent's output screen (command output lands in the
  207. terminal that spawned it). */
  208. procs[slot].screen = procs[current_pid].screen;
  209. irq_restore(flags);
  210. return (int)procs[slot].pid;
  211. }
  212. int process_create(const char *name, void (*entry)(void))
  213. {
  214. return setup_process(name, (unsigned int)entry, 0, (void *)0);
  215. }
  216. int process_create_arg(const char *name, void (*entry)(const char *),
  217. const char *arg)
  218. {
  219. return setup_process(name, (unsigned int)entry, 1, arg);
  220. }
  221. /* Create a process whose entry takes a raw pointer argument (no string copy). */
  222. int process_create_ptr(const char *name, void (*entry)(void *), void *arg)
  223. {
  224. int slot, owned;
  225. unsigned int base, top, *sp, cr3;
  226. unsigned int flags;
  227. flags = irq_save_disable();
  228. slot = alloc_slot();
  229. if (slot < 0) {
  230. irq_restore(flags);
  231. return -1;
  232. }
  233. cr3 = paging_new_directory();
  234. if (!cr3) {
  235. irq_restore(flags);
  236. return -1;
  237. }
  238. base = stack_alloc(&owned);
  239. if (!base) {
  240. mm_free_page(cr3);
  241. irq_restore(flags);
  242. return -1;
  243. }
  244. top = base + PROC_STACK_SIZE;
  245. sp = (unsigned int *)top;
  246. *--sp = (unsigned int)arg; /* first C parameter */
  247. *--sp = (unsigned int)process_exit;/* return address */
  248. *--sp = 0x202; /* EFLAGS: IF=1 */
  249. *--sp = 0x08; /* CS */
  250. *--sp = (unsigned int)entry; /* EIP */
  251. *--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0; /* EAX ECX EDX EBX */
  252. *--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0; /* ESP EBP ESI EDI */
  253. procs[slot].esp = (unsigned int)sp;
  254. procs[slot].state = PROC_READY;
  255. procs[slot].pid = next_pid_counter++;
  256. procs[slot].stack_base = owned ? base : 0;
  257. procs[slot].cr3 = cr3;
  258. procs[slot].kstack_top = top;
  259. name_copy(procs[slot].name, name);
  260. procs[slot].screen = procs[current_pid].screen;
  261. irq_restore(flags);
  262. return (int)procs[slot].pid;
  263. }
  264. /* Load an ELF image into a fresh address space and run it as a ring-3 process. */
  265. int process_create_user(const char *name, const void *image, unsigned int size,
  266. const char *arg, const char *cwd)
  267. {
  268. int slot, owned;
  269. unsigned int base, top, *sp, cr3, entry;
  270. unsigned int flags;
  271. int i;
  272. flags = irq_save_disable();
  273. slot = alloc_slot();
  274. if (slot < 0) {
  275. irq_restore(flags);
  276. return -1;
  277. }
  278. cr3 = paging_new_directory();
  279. if (!cr3) {
  280. irq_restore(flags);
  281. return -1;
  282. }
  283. entry = elf_load(cr3, image, size);
  284. if (!entry) {
  285. mm_free_page(cr3);
  286. irq_restore(flags);
  287. return -2; /* not a loadable ELF */
  288. }
  289. /* Map the user stack just below USER_STACK_TOP. Keep the top page's
  290. * physical address: the argument string is written through it (identity
  291. * mapped) after it is mapped in `cr3`. */
  292. {
  293. unsigned int top_phys = 0;
  294. unsigned int user_esp = USER_STACK_TOP;
  295. for (i = 0; i < USER_STACK_PAGES; i++) {
  296. unsigned int phys = mm_alloc_page();
  297. unsigned int va = USER_STACK_TOP - (unsigned int)(i + 1) * 0x1000;
  298. if (!phys ||
  299. !paging_map_page(cr3, va, phys,
  300. PTE_USER | PTE_WRITABLE | PTE_PRESENT)) {
  301. mm_free_page(cr3);
  302. irq_restore(flags);
  303. return -1;
  304. }
  305. if (i == 0)
  306. top_phys = phys;
  307. }
  308. /* One C string argument at the top of the user stack with a fake
  309. * return address below it, so `_start(const char *arg)` reads it
  310. * as its first parameter without needing a crt0. The virtual
  311. * addresses go into the frame; the writes go through the identity
  312. * map at the same offset from the physical page top. */
  313. {
  314. unsigned int va_top = USER_STACK_TOP;
  315. unsigned char *base_phys = (unsigned char *)(top_phys + 0x1000);
  316. unsigned char *str_phys;
  317. unsigned int *frame_phys;
  318. unsigned int len = 0;
  319. unsigned int va, k;
  320. if (arg)
  321. while (arg[len])
  322. len++;
  323. va = (va_top - (len + 1)) & ~15u;
  324. if (va - 8 < USER_STACK_TOP - USER_STACK_PAGES * 0x1000) {
  325. mm_free_page(cr3);
  326. irq_restore(flags);
  327. return -1; /* argument does not fit the stack */
  328. }
  329. str_phys = base_phys - (va_top - va);
  330. for (k = 0; k <= len; k++)
  331. str_phys[k] = arg ? arg[k] : '\0';
  332. frame_phys = (unsigned int *)(str_phys - 8);
  333. frame_phys[0] = 0; /* fake return address */
  334. frame_phys[1] = va; /* the argument pointer (user VA) */
  335. user_esp = va - 8;
  336. }
  337. base = stack_alloc(&owned);
  338. if (!base) {
  339. mm_free_page(cr3);
  340. irq_restore(flags);
  341. return -1;
  342. }
  343. top = base + PROC_STACK_SIZE;
  344. sp = (unsigned int *)top;
  345. *--sp = 0x23; /* SS: user data */
  346. *--sp = user_esp; /* ESP: user stack + arg frame */
  347. *--sp = 0x202; /* EFLAGS: IF=1 */
  348. *--sp = 0x1B; /* CS: user code */
  349. *--sp = entry; /* EIP */
  350. *--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0; /* EAX ECX EDX EBX */
  351. *--sp = 0; *--sp = 0; *--sp = 0; *--sp = 0; /* ESP EBP ESI EDI */
  352. }
  353. procs[slot].esp = (unsigned int)sp;
  354. procs[slot].state = PROC_READY;
  355. procs[slot].pid = next_pid_counter++;
  356. procs[slot].stack_base = owned ? base : 0;
  357. procs[slot].cr3 = cr3;
  358. procs[slot].kstack_top = top;
  359. name_copy(procs[slot].name, name);
  360. procs[slot].screen = procs[current_pid].screen;
  361. {
  362. unsigned int k;
  363. for (k = 0; cwd && cwd[k] && k + 1 < sizeof(procs[slot].cwd); k++)
  364. procs[slot].cwd[k] = cwd[k];
  365. procs[slot].cwd[k] = '\0';
  366. }
  367. irq_restore(flags);
  368. return (int)procs[slot].pid;
  369. }
  370. /* Set the output screen of the currently-running process (used by a terminal
  371. at startup to bind itself to its own screen). */
  372. void process_set_screen(struct text_screen *screen)
  373. {
  374. procs[current_pid].screen = screen;
  375. }
  376. void process_map_mmio_all(unsigned int phys_base, unsigned int size)
  377. {
  378. unsigned int i, kernel_cr3 = paging_current_cr3();
  379. paging_map_mmio(phys_base, size);
  380. for (i = 0; i < proc_cap; i++) {
  381. if (procs[i].state == PROC_UNUSED || procs[i].state == PROC_DEAD)
  382. continue;
  383. if (procs[i].cr3 && procs[i].cr3 != kernel_cr3)
  384. paging_map_mmio_cr3(procs[i].cr3, phys_base, size);
  385. }
  386. }
  387. void process_exit(void)
  388. {
  389. procs[current_pid].state = PROC_DEAD;
  390. __asm__ volatile ("sti"); /* re-enable IRQs so the PIT can switch us out */
  391. for (;;)
  392. __asm__ volatile ("hlt");
  393. }
  394. /*
  395. * Round-robin scheduler. Called from the PIT IRQ stub with interrupts
  396. * disabled. Picks the next runnable process and updates current_pid.
  397. * The caller (switch.S) takes care of actually switching ESP.
  398. */
  399. void schedule(void)
  400. {
  401. unsigned int i, next;
  402. /* Reap dead processes, freeing their stacks. Skip the current slot: we
  403. * may be running on its stack right now (it just called process_exit),
  404. * so it is reaped on a later schedule() from another process's context. */
  405. for (i = 0; i < proc_cap; i++) {
  406. if (procs[i].state == PROC_DEAD && i != current_pid) {
  407. sys_net_reap(procs[i].pid); /* release a held NIC */
  408. if (procs[i].stack_base)
  409. mm_free_page(procs[i].stack_base);
  410. if (procs[i].cr3 && procs[i].cr3 != paging_current_cr3())
  411. mm_free_page(procs[i].cr3);
  412. procs[i].stack_base = 0;
  413. procs[i].cr3 = 0;
  414. procs[i].state = PROC_UNUSED;
  415. }
  416. }
  417. /* A file syscall is in progress: stay on the current process so the FAT
  418. * driver's static state is never touched concurrently (see sys_fs.c).
  419. * Interrupts stay enabled, so the disk's IRQs are still serviced. */
  420. if (sys_fs_busy) {
  421. if (procs[current_pid].state == PROC_READY)
  422. procs[current_pid].state = PROC_RUNNING;
  423. return;
  424. }
  425. /* Wake sleeping processes whose deadline has passed. */
  426. for (i = 0; i < proc_cap; i++) {
  427. if (procs[i].state == PROC_SLEEPING &&
  428. (int)(procs[i].wake_ms - get_ticks_ms()) <= 0)
  429. procs[i].state = PROC_READY;
  430. }
  431. /* Mark current as READY (it was RUNNING). */
  432. if (procs[current_pid].state == PROC_RUNNING)
  433. procs[current_pid].state = PROC_READY;
  434. /* Find next runnable slot. */
  435. next = current_pid;
  436. for (i = 0; i < proc_cap; i++) {
  437. next = (next + 1) % proc_cap;
  438. if (procs[next].state == PROC_READY) {
  439. procs[next].state = PROC_RUNNING;
  440. current_pid = next;
  441. return;
  442. }
  443. }
  444. /* Nothing else runnable -- stay on current if still alive. */
  445. if (procs[current_pid].state == PROC_READY) {
  446. procs[current_pid].state = PROC_RUNNING;
  447. return;
  448. }
  449. /* Everything dead: fall back to slot 0 (window manager). */
  450. procs[0].state = PROC_RUNNING;
  451. current_pid = 0;
  452. }
  453. /* ---- user-facing helpers ---- */
  454. static const char *state_str(unsigned int s)
  455. {
  456. switch (s) {
  457. case PROC_RUNNING: return "run ";
  458. case PROC_READY: return "ready";
  459. default: return "? ";
  460. }
  461. }
  462. static void put_dec(unsigned int n)
  463. {
  464. char buf[12];
  465. unsigned int i = sizeof(buf) - 1;
  466. buf[i] = '\0';
  467. if (n == 0) {
  468. io_putchar('0');
  469. return;
  470. }
  471. while (n && i > 0) {
  472. buf[--i] = (char)('0' + (n % 10));
  473. n /= 10;
  474. }
  475. io_putstr(buf + i);
  476. }
  477. void process_ps(void)
  478. {
  479. unsigned int i;
  480. io_putstr("PID STATE NAME\n");
  481. for (i = 0; i < proc_cap; i++) {
  482. if (procs[i].state == PROC_UNUSED || procs[i].state == PROC_DEAD)
  483. continue;
  484. io_putchar(' ');
  485. put_dec(procs[i].pid);
  486. io_putstr(" ");
  487. io_putstr(state_str(procs[i].state));
  488. io_putstr(" ");
  489. io_putstr(procs[i].name);
  490. io_putchar('\n');
  491. }
  492. }
  493. int process_kill(unsigned int pid)
  494. {
  495. unsigned int i;
  496. if (pid == 0)
  497. return -1; /* cannot kill window manager */
  498. for (i = 1; i < proc_cap; i++) {
  499. if (procs[i].state != PROC_UNUSED && procs[i].state != PROC_DEAD &&
  500. procs[i].pid == pid) {
  501. procs[i].state = PROC_DEAD;
  502. return 0;
  503. }
  504. }
  505. return -1;
  506. }
  507. /* Return 1 if a process with `pid` is still alive (READY/RUNNING/SLEEPING). */
  508. int process_is_alive(unsigned int pid)
  509. {
  510. unsigned int i;
  511. for (i = 0; i < proc_cap; i++)
  512. if (procs[i].pid == pid &&
  513. (procs[i].state == PROC_READY ||
  514. procs[i].state == PROC_RUNNING ||
  515. procs[i].state == PROC_SLEEPING))
  516. return 1;
  517. return 0;
  518. }
  519. /* Block the current process for `ms` milliseconds. Marks it sleeping and
  520. * yields to the scheduler; it is woken when its deadline passes. */
  521. void process_sleep_ms(unsigned int ms)
  522. {
  523. procs[current_pid].wake_ms = get_ticks_ms() + ms;
  524. procs[current_pid].state = PROC_SLEEPING;
  525. __asm__ volatile ("sti"); /* re-enable IRQs so the PIT can switch us out */
  526. while (procs[current_pid].state == PROC_SLEEPING)
  527. cpu_idle();
  528. }
  529. /* Wait (yield) until the process with `pid` has exited. */
  530. void process_wait(unsigned int pid)
  531. {
  532. while (process_is_alive(pid))
  533. process_sleep_ms(10);
  534. }