kernel.c 14 KB

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