process.c 16 KB

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