process.c 15 KB

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