kernel.c 17 KB

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