kernel.c 15 KB

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