kernel.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. /* Boot-stage timing: written to COM1, which the netlog mirror forwards to
  235. * `make netmon` on boards without a serial port. */
  236. static unsigned int boot_t0;
  237. static void boot_trace(const char *what)
  238. {
  239. serial_puts(SERIAL_COM1, "[boot] ");
  240. serial_puts(SERIAL_COM1, what);
  241. serial_puts(SERIAL_COM1, " +");
  242. serial_putdec(SERIAL_COM1, get_ticks_ms() - boot_t0);
  243. serial_puts(SERIAL_COM1, " ms\n");
  244. }
  245. void kernel_main(void);
  246. void kernel_main(void)
  247. {
  248. unsigned char *p = __bss_start;
  249. while (p < __bss_end)
  250. *p++ = 0;
  251. serial_init(SERIAL_COM1);
  252. serial_ring_init();
  253. /* Network console mirror from the very first line on; the ring holds the
  254. * early boot output until the WM loop starts flushing it. */
  255. netlog_init();
  256. serial_puts(SERIAL_COM1, "\n" OS_NAME " v" OS_VERSION " booted\n");
  257. /* GDT/TSS and the per-CPU GS base must exist before anything that can
  258. * use current_proc()/this_cpu(). The BSS is already cleared and the
  259. * GDT/TSS live at identity-mapped addresses. */
  260. gdt_tss_init(0);
  261. mm_init();
  262. mm_dump();
  263. kmalloc_init();
  264. paging_init();
  265. /* paging_init only ORs in PSE; make sure the BSP's SSE state is on
  266. * before any drawing path can select an SSE2 helper. */
  267. cpu_enable_sse();
  268. /* ACPI needs paging for table access; a missing or unusable MADT simply
  269. * leaves the machine at one CPU. */
  270. acpi_init();
  271. acpi_dump();
  272. io_init();
  273. idle_init();
  274. thermal_init();
  275. /* process_init must run before timer_init: once the PIT is started (sti
  276. * in timer_init) the context-switch stub runs on every tick and reads
  277. * the current process, its CR3 and the TSS, so those must be valid. */
  278. process_init();
  279. timer_init();
  280. boot_t0 = get_ticks_ms();
  281. boot_trace("timer");
  282. /* The PIT (and its sti) is live, so the AP bring-up can use it as a
  283. * timeout clock. APs idle until smp_enable_sched() after boot. */
  284. smp_init();
  285. boot_trace("smp");
  286. mouse_init();
  287. /* USB HID backend (mouse + keyboard): controller bring-up + first
  288. * scan; devices plugged in later are picked up by the hotplug
  289. * watcher in the WM loop. */
  290. usbhid_init();
  291. boot_trace("usb");
  292. vga_shadow_init();
  293. vga_fb_flush();
  294. boot_trace("vga");
  295. /* The command pack: read-only, mounted at /ramfs (see ramfs.c). This
  296. * happens before the block-device scan because the WM and terminal are
  297. * loaded from /ramfs, not from a disk. */
  298. {
  299. extern unsigned char _binary_cmds_pack_gz_bin_start[];
  300. extern unsigned char _binary_cmds_pack_gz_bin_end[];
  301. unsigned int pack_len =
  302. (unsigned int)(_binary_cmds_pack_gz_bin_end -
  303. _binary_cmds_pack_gz_bin_start);
  304. if (ramfs_init(_binary_cmds_pack_gz_bin_start, pack_len) != 0)
  305. serial_puts(SERIAL_COM1, "ramfs: bad pack\n");
  306. else {
  307. serial_puts(SERIAL_COM1, "ramfs: pack ok, ");
  308. serial_putdec(SERIAL_COM1, ramfs_count());
  309. serial_puts(SERIAL_COM1, " files, ");
  310. serial_putdec(SERIAL_COM1, pack_len);
  311. serial_puts(SERIAL_COM1, " -> ");
  312. serial_putdec(SERIAL_COM1, ramfs_pack_size());
  313. serial_puts(SERIAL_COM1, " bytes\n");
  314. vfs_mount_ramfs();
  315. }
  316. }
  317. boot_trace("ramfs");
  318. /* Start the WM before touching disks: the first frame can be painted
  319. * while storage and the network are still being probed. */
  320. wm_server_init();
  321. wm_server_start();
  322. boot_trace("wm");
  323. /* Probe the NIC (link negotiation is asynchronous now) before the
  324. * kworker starts, so its netlog flushes have a device to use. */
  325. netdev_active();
  326. boot_trace("net");
  327. /* The idle process is the kernel_main context; housekeeping runs in
  328. * its own process so it cannot be starved by a busy system. */
  329. kworker_pid = process_create("kworker", kworker_main);
  330. if (kworker_pid < 0) {
  331. serial_puts(SERIAL_COM1, "kworker: cannot create, using idle fallback\n");
  332. kworker_pid = -1;
  333. } else {
  334. process_set_weight((unsigned int)kworker_pid, 1);
  335. process_set_affinity((unsigned int)kworker_pid, 1);
  336. }
  337. boot_trace("kworker");
  338. /* Slow storage bring-up happens behind the usable desktop now. */
  339. boot_trace("storage begin");
  340. vfs_mount_all();
  341. boot_trace("storage");
  342. /* The first terminal is spawned only now: while the boot scan was
  343. * rebuilding the mount table, no user command could touch the disks.
  344. * The desktop itself was already painted from /ramfs. */
  345. wm_spawn_terminal();
  346. boot_trace("terminal");
  347. /* With a NIC present, try DHCP; on failure the static default stays.
  348. * Deliberately after the WM: a missing cable or DHCP server must not
  349. * delay the first frame. */
  350. if (netdev_active())
  351. dhcp_run(3000);
  352. boot_trace("dhcp");
  353. /* Boot-time device/FS setup is complete; APs may now take user work.
  354. * Kernel threads stay pinned to the BSP and serialize on the BKL. */
  355. smp_enable_sched();
  356. boot_trace("sched");
  357. kernel_idle_loop();
  358. }