kernel.c 14 KB

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