kernel.c 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /* Kernel: entry point at 0x7E00, timer (PIT 1 kHz), process init, terminal. */
  2. #include "idle.h"
  3. #include "io.h"
  4. #include "panic.h"
  5. #include "kmalloc.h"
  6. #include "mm.h"
  7. #include "mouse.h"
  8. #include "netdev.h"
  9. #include "dhcp.h"
  10. #include "netlog.h"
  11. #include "paging.h"
  12. #include "process.h"
  13. #include "ramfs.h"
  14. #include "sys_gfx.h"
  15. #include "timer.h"
  16. #include "tss.h"
  17. #include "usbhid.h"
  18. #include "wm.h"
  19. #include "serial.h"
  20. #include "version.h"
  21. #include "vga.h"
  22. #include "vfs.h"
  23. static inline void outb(unsigned short port, unsigned char v)
  24. {
  25. __asm__ volatile ("outb %0, %1" : : "a"(v), "Nd"(port));
  26. }
  27. volatile unsigned int ticks;
  28. struct idt_entry {
  29. unsigned short offset_lo;
  30. unsigned short selector;
  31. unsigned char zero;
  32. unsigned char type;
  33. unsigned short offset_hi;
  34. } __attribute__((packed));
  35. struct idtr_desc {
  36. unsigned short limit;
  37. unsigned int base;
  38. } __attribute__((packed));
  39. static struct idt_entry idt[256];
  40. static struct idtr_desc idtr;
  41. extern void pit_irq_stub(void);
  42. extern void kbd_irq_stub(void);
  43. extern void fdc_irq_stub(void);
  44. extern void default_irq_stub(void);
  45. extern void resched_stub(void);
  46. extern void syscall_stub(void);
  47. extern unsigned int exc_stub_table[];
  48. unsigned int get_ticks_ms(void)
  49. {
  50. return ticks;
  51. }
  52. void exc_handler(struct exc_state *st);
  53. void exc_handler(struct exc_state *st)
  54. {
  55. unsigned int vector = st->vector;
  56. unsigned int cr2 = 0;
  57. static const char * const names[] = {
  58. "#DE Divide Error", "#DB Debug", "NMI", "#BP Breakpoint",
  59. "#OF Overflow", "#BR Bound Range", "#UD Invalid Opcode",
  60. "#NM No FPU", "#DF Double Fault", "Coprocessor Overrun",
  61. "#TS Invalid TSS", "#NP Seg Not Present", "#SS Stack Fault",
  62. "#GP General Protection", "#PF Page Fault", "Reserved",
  63. "#MF FPU Error", "#AC Alignment Check", "#MC Machine Check",
  64. "#XM SIMD Error",
  65. };
  66. __asm__ volatile ("mov %%cr2, %0" : "=r"(cr2));
  67. /* A fault from ring 3 is a bug in a user command (or its ELF): kill that
  68. * process and keep the kernel running. Kernel faults still halt. */
  69. if ((st->cs & 3) == 3) {
  70. serial_puts(SERIAL_COM1, "\n*** user fault vec ");
  71. serial_puthex(SERIAL_COM1, vector);
  72. serial_puts(SERIAL_COM1, " eip=");
  73. serial_puthex(SERIAL_COM1, st->eip);
  74. serial_puts(SERIAL_COM1, " cr2=");
  75. serial_puthex(SERIAL_COM1, cr2);
  76. serial_puts(SERIAL_COM1, " -- process killed\n");
  77. io_putstr("\n*** fault: ");
  78. io_putstr(vector < 20 ? names[vector] : "unknown vector");
  79. io_putstr(" -- command killed\n");
  80. process_exit(); /* marks us dead and waits to be switched out */
  81. }
  82. /* Fatal kernel fault: the banner goes straight into the LFB (no serial
  83. * console needed) and the full state is mirrored to COM1. */
  84. panic_report(st, vector < 20 ? names[vector] : "unknown vector");
  85. for (;;)
  86. __asm__ volatile ("cli; hlt");
  87. }
  88. static void set_idt_gate(int vec, unsigned int handler)
  89. {
  90. idt[vec].offset_lo = (unsigned short)(handler & 0xFFFF);
  91. idt[vec].selector = 0x08;
  92. idt[vec].zero = 0;
  93. idt[vec].type = 0x8E;
  94. idt[vec].offset_hi = (unsigned short)((handler >> 16) & 0xFFFF);
  95. }
  96. /* Trap gate (DPL=3) so ring-3 can `int` into it; a trap gate does NOT clear
  97. * IF, so a blocking syscall (e.g. sleep) can still be preempted by the timer. */
  98. static void set_idt_gate_user(int vec, unsigned int handler)
  99. {
  100. idt[vec].offset_lo = (unsigned short)(handler & 0xFFFF);
  101. idt[vec].selector = 0x08;
  102. idt[vec].zero = 0;
  103. idt[vec].type = 0xEF;
  104. idt[vec].offset_hi = (unsigned short)((handler >> 16) & 0xFFFF);
  105. }
  106. static void timer_init(void)
  107. {
  108. int i;
  109. /* Remap PICs: master at 0x20, slave at 0x28. */
  110. outb(0x20, 0x11);
  111. outb(0xA0, 0x11);
  112. outb(0x21, 0x20);
  113. outb(0xA1, 0x28);
  114. outb(0x21, 0x04);
  115. outb(0xA1, 0x02);
  116. outb(0x21, 0x01);
  117. outb(0xA1, 0x01);
  118. outb(0x21, 0xFC);
  119. outb(0xA1, 0xFF);
  120. /* Default handler for all 256 vectors: absorbs any unexpected
  121. interrupt (including spurious IRQ 7) with an EOI + iret. */
  122. for (i = 0; i < 256; i++)
  123. set_idt_gate(i, (unsigned int)default_irq_stub);
  124. /* Exception handlers 0-31: ring-3 faults kill the process, kernel
  125. faults print the panic banner and halt (see exc_handler). */
  126. for (i = 0; i < 32; i++)
  127. set_idt_gate(i, exc_stub_table[i]);
  128. /* Hardware IRQ handlers. */
  129. set_idt_gate(0x20, (unsigned int)pit_irq_stub);
  130. set_idt_gate(0x21, (unsigned int)kbd_irq_stub);
  131. set_idt_gate(0x26, (unsigned int)fdc_irq_stub);
  132. /* Syscall gate (ring-3 can int 0x80). */
  133. set_idt_gate_user(0x80, (unsigned int)syscall_stub);
  134. /* Kernel-only voluntary reschedule gate (int 0x81). */
  135. set_idt_gate(0x81, (unsigned int)resched_stub);
  136. idtr.limit = (unsigned short)(sizeof(idt) - 1);
  137. idtr.base = (unsigned int)idt;
  138. __asm__ volatile ("lidt %0" : : "m"(idtr));
  139. outb(0x43, 0x36);
  140. outb(0x40, (unsigned char)(1193 & 0xFF));
  141. outb(0x40, (unsigned char)((1193 >> 8) & 0xFF));
  142. __asm__ volatile ("sti");
  143. }
  144. extern unsigned char __bss_start[], __bss_end[];
  145. static int kworker_pid = -1;
  146. /* Parts of the system that must keep running independently of the WM:
  147. * input routing, cursor blink, kexec recovery, netlog flushing, gfx-session
  148. * cleanup and the shadow-buffer flush. */
  149. static void system_housekeeping(void)
  150. {
  151. process_reap_dead();
  152. mouse_poll_update();
  153. wm_pump_keyboard();
  154. wm_blink_cursor();
  155. netlog_flush();
  156. wm_handle_kexec();
  157. wm_server_supervise();
  158. if (wm_server_can_reap())
  159. sys_gfx_collect();
  160. if (!wm_server_frame_active())
  161. vga_fb_flush_budget(VGA_FLUSH_BUDGET_BYTES);
  162. }
  163. static void kworker_main(void)
  164. {
  165. for (;;) {
  166. system_housekeeping();
  167. process_sleep_ms(5);
  168. }
  169. }
  170. /* Idle is not a normal runnable task: schedule() selects it only when no
  171. * READY process exists. The kworker does the housekeeping; if it dies (or
  172. * could not be created), idle takes over as a degraded fallback. */
  173. static void kernel_idle_loop(void)
  174. {
  175. for (;;) {
  176. if (kworker_pid <= 0 ||
  177. !process_is_alive((unsigned int)kworker_pid))
  178. system_housekeeping();
  179. cpu_idle();
  180. }
  181. }
  182. void kernel_main(void);
  183. void kernel_main(void)
  184. {
  185. unsigned char *p = __bss_start;
  186. while (p < __bss_end)
  187. *p++ = 0;
  188. serial_init(SERIAL_COM1);
  189. serial_ring_init();
  190. /* Network console mirror from the very first line on; the ring holds the
  191. * early boot output until the WM loop starts flushing it. */
  192. netlog_init();
  193. serial_puts(SERIAL_COM1, "\n" OS_NAME " v" OS_VERSION " booted\n");
  194. /* GDT/TSS and the per-CPU GS base must exist before anything that can
  195. * use current_proc()/this_cpu(). The BSS is already cleared and the
  196. * GDT/TSS live at identity-mapped addresses. */
  197. gdt_tss_init(0);
  198. mm_init();
  199. mm_dump();
  200. kmalloc_init();
  201. paging_init();
  202. io_init();
  203. idle_init();
  204. /* process_init must run before timer_init: once the PIT is started (sti
  205. * in timer_init) the context-switch stub runs on every tick and reads
  206. * the current process, its CR3 and the TSS, so those must be valid. */
  207. process_init();
  208. timer_init();
  209. mouse_init();
  210. /* USB HID backend (mouse + keyboard): controller bring-up + first
  211. * scan; devices plugged in later are picked up by the hotplug
  212. * watcher in the WM loop. */
  213. usbhid_init();
  214. vga_shadow_init();
  215. vga_fb_flush();
  216. vfs_mount_all();
  217. /* The command pack: read-only, mounted at /ramfs (see ramfs.c). */
  218. {
  219. extern unsigned char _binary_cmds_pack_start[];
  220. extern unsigned char _binary_cmds_pack_end[];
  221. unsigned int pack_len = (unsigned int)(_binary_cmds_pack_end -
  222. _binary_cmds_pack_start);
  223. if (ramfs_init(_binary_cmds_pack_start, pack_len) != 0)
  224. serial_puts(SERIAL_COM1, "ramfs: bad pack\n");
  225. else {
  226. serial_puts(SERIAL_COM1, "ramfs: pack ok, ");
  227. serial_putdec(SERIAL_COM1, ramfs_count());
  228. serial_puts(SERIAL_COM1, " files\n");
  229. vfs_mount_ramfs();
  230. }
  231. }
  232. /* Bring the NIC up before the WM loop starts, so an idle board can pick
  233. * up a network kexec (`make net-dev`) without any typing. */
  234. netdev_active();
  235. /* With a NIC present, try DHCP; on failure the static default stays. */
  236. if (netdev_active())
  237. dhcp_run(3000);
  238. /* The idle process is the kernel_main context; the ring-3 WM is spawned
  239. * from /ramfs/bin/wm. Housekeeping runs in its own process so it cannot
  240. * be starved by a busy system. */
  241. wm_server_init();
  242. wm_server_start();
  243. kworker_pid = process_create("kworker", kworker_main);
  244. if (kworker_pid < 0) {
  245. serial_puts(SERIAL_COM1, "kworker: cannot create, using idle fallback\n");
  246. kworker_pid = -1;
  247. } else {
  248. process_set_weight((unsigned int)kworker_pid, 1);
  249. process_set_affinity((unsigned int)kworker_pid, 1);
  250. }
  251. kernel_idle_loop();
  252. }