process.c 14 KB

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