kernel.c 15 KB

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