kernel.c 11 KB

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