kernel.c 17 KB

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