kernel.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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 "init.h"
  10. #include "io.h"
  11. #include "ioapic.h"
  12. #include "lapic.h"
  13. #include "panic.h"
  14. #include "kmalloc.h"
  15. #include "mm.h"
  16. #include "mouse.h"
  17. #include "netdev.h"
  18. #include "net.h"
  19. #include "dhcp.h"
  20. #include "netlog.h"
  21. #include "paging.h"
  22. #include "power.h"
  23. #include "process.h"
  24. #include "ramfs.h"
  25. #include "cursor.h"
  26. #include "rndis.h"
  27. #include "rtl8821au.h"
  28. #include "sched.h"
  29. #include "sys_fs.h"
  30. #include "sys_wm.h"
  31. #include "thermal.h"
  32. #include "timer.h"
  33. #include "tpec.h"
  34. #include "tss.h"
  35. #include "usbhid.h"
  36. #include "usbmsc.h"
  37. #include "wm.h"
  38. #include "serial.h"
  39. #include "smp.h"
  40. #include "version.h"
  41. #include "vga.h"
  42. #include "vfs.h"
  43. #include "wifi_cfg.h"
  44. static inline void outb(unsigned short port, unsigned char v)
  45. {
  46. __asm__ volatile ("outb %0, %1" : : "a"(v), "Nd"(port));
  47. }
  48. volatile unsigned int ticks;
  49. static unsigned int timer_hz;
  50. static unsigned int tick_ms = 1;
  51. struct idt_entry {
  52. unsigned short offset_lo;
  53. unsigned short selector;
  54. unsigned char zero;
  55. unsigned char type;
  56. unsigned short offset_hi;
  57. } __attribute__((packed));
  58. struct idtr_desc {
  59. unsigned short limit;
  60. unsigned int base;
  61. } __attribute__((packed));
  62. static struct idt_entry idt[256];
  63. static struct idtr_desc idtr;
  64. extern void pit_irq_stub(void);
  65. extern void kbd_irq_stub(void);
  66. extern void mouse_irq_stub(void);
  67. extern void fdc_irq_stub(void);
  68. extern void default_irq_stub(void);
  69. extern void resched_stub(void);
  70. extern void lapic_timer_stub(void);
  71. extern void lapic_resched_stub(void);
  72. extern void lapic_spurious_stub(void);
  73. extern void syscall_stub(void);
  74. extern unsigned int exc_stub_table[];
  75. unsigned int get_ticks_ms(void)
  76. {
  77. return ticks;
  78. }
  79. unsigned int timer_tick_ms(void)
  80. {
  81. return tick_ms;
  82. }
  83. void timer_tick_advance(void)
  84. {
  85. ticks += tick_ms;
  86. }
  87. void timer_set_hz(unsigned int hz)
  88. {
  89. unsigned int flags, divisor;
  90. if (hz < 100 || hz > 1000)
  91. hz = 1000;
  92. if (hz == timer_hz)
  93. return;
  94. __asm__ volatile ("pushfl; popl %0" : "=r"(flags));
  95. __asm__ volatile ("cli" ::: "memory");
  96. timer_hz = hz;
  97. tick_ms = 1000 / hz;
  98. divisor = 1193182u / hz;
  99. outb(0x43, 0x36);
  100. outb(0x40, (unsigned char)(divisor & 0xFF));
  101. outb(0x40, (unsigned char)((divisor >> 8) & 0xFF));
  102. if (flags & (1u << 9))
  103. __asm__ volatile ("sti" ::: "memory");
  104. }
  105. void exc_handler(struct exc_state *st);
  106. void exc_handler(struct exc_state *st)
  107. {
  108. unsigned int vector = st->vector;
  109. unsigned int cr2 = 0;
  110. static const char * const names[] = {
  111. "#DE Divide Error", "#DB Debug", "NMI", "#BP Breakpoint",
  112. "#OF Overflow", "#BR Bound Range", "#UD Invalid Opcode",
  113. "#NM No FPU", "#DF Double Fault", "Coprocessor Overrun",
  114. "#TS Invalid TSS", "#NP Seg Not Present", "#SS Stack Fault",
  115. "#GP General Protection", "#PF Page Fault", "Reserved",
  116. "#MF FPU Error", "#AC Alignment Check", "#MC Machine Check",
  117. "#XM SIMD Error",
  118. };
  119. __asm__ volatile ("mov %%cr2, %0" : "=r"(cr2));
  120. /* A fault from ring 3 is a bug in a user command (or its ELF): kill that
  121. * process and keep the kernel running. Kernel faults still halt. */
  122. if ((st->cs & 3) == 3) {
  123. struct process *p = current_proc();
  124. serial_puts(SERIAL_COM1, "\n*** user fault vec ");
  125. serial_puthex(SERIAL_COM1, vector);
  126. serial_puts(SERIAL_COM1, " eip=");
  127. serial_puthex(SERIAL_COM1, st->eip);
  128. serial_puts(SERIAL_COM1, " cr2=");
  129. serial_puthex(SERIAL_COM1, cr2);
  130. if (p) {
  131. serial_puts(SERIAL_COM1, " pid=");
  132. serial_putdec(SERIAL_COM1, p->pid);
  133. serial_puts(SERIAL_COM1, " ");
  134. serial_puts(SERIAL_COM1, p->name);
  135. }
  136. serial_puts(SERIAL_COM1, " -- process killed\n");
  137. io_putstr("\n*** fault: ");
  138. io_putstr(vector < 20 ? names[vector] : "unknown vector");
  139. io_putstr(" -- command killed\n");
  140. process_exit(); /* marks us dead and waits to be switched out */
  141. }
  142. /* Fatal kernel fault: the banner goes straight into the LFB (no serial
  143. * console needed) and the full state is mirrored to COM1. */
  144. panic_report(st, vector < 20 ? names[vector] : "unknown vector");
  145. for (;;)
  146. __asm__ volatile ("cli; hlt");
  147. }
  148. static void set_idt_gate(int vec, unsigned int handler)
  149. {
  150. idt[vec].offset_lo = (unsigned short)(handler & 0xFFFF);
  151. idt[vec].selector = 0x08;
  152. idt[vec].zero = 0;
  153. idt[vec].type = 0x8E;
  154. idt[vec].offset_hi = (unsigned short)((handler >> 16) & 0xFFFF);
  155. }
  156. /* Trap gate (DPL=3) so ring-3 can `int` into it; a trap gate does NOT clear
  157. * IF, so a blocking syscall (e.g. sleep) can still be preempted by the timer. */
  158. static void set_idt_gate_user(int vec, unsigned int handler)
  159. {
  160. idt[vec].offset_lo = (unsigned short)(handler & 0xFFFF);
  161. idt[vec].selector = 0x08;
  162. idt[vec].zero = 0;
  163. idt[vec].type = 0xEF;
  164. idt[vec].offset_hi = (unsigned short)((handler >> 16) & 0xFFFF);
  165. }
  166. static void timer_init(void)
  167. {
  168. int i;
  169. /* Remap PICs: master at 0x20, slave at 0x28. */
  170. outb(0x20, 0x11);
  171. outb(0xA0, 0x11);
  172. outb(0x21, 0x20);
  173. outb(0xA1, 0x28);
  174. outb(0x21, 0x04);
  175. outb(0xA1, 0x02);
  176. outb(0x21, 0x01);
  177. outb(0xA1, 0x01);
  178. outb(0x21, 0xFC);
  179. outb(0xA1, 0xFF);
  180. /* Default handler for all 256 vectors: absorbs any unexpected
  181. interrupt (including spurious IRQ 7) with an EOI + iret. */
  182. for (i = 0; i < 256; i++)
  183. set_idt_gate(i, (unsigned int)default_irq_stub);
  184. /* Exception handlers 0-31: ring-3 faults kill the process, kernel
  185. faults print the panic banner and halt (see exc_handler). */
  186. for (i = 0; i < 32; i++)
  187. set_idt_gate(i, exc_stub_table[i]);
  188. /* Hardware IRQ handlers. */
  189. set_idt_gate(0x20, (unsigned int)pit_irq_stub);
  190. set_idt_gate(0x21, (unsigned int)kbd_irq_stub);
  191. set_idt_gate(0x2c, (unsigned int)mouse_irq_stub);
  192. set_idt_gate(0x26, (unsigned int)fdc_irq_stub);
  193. /* Local-APIC vectors: the AP timer and reschedule IPI, plus the
  194. * spurious vector the LAPIC can deliver at any time. */
  195. set_idt_gate(LAPIC_TIMER_VECTOR, (unsigned int)lapic_timer_stub);
  196. set_idt_gate(LAPIC_RESCHED_VECTOR, (unsigned int)lapic_resched_stub);
  197. set_idt_gate(LAPIC_SPURIOUS_VECTOR, (unsigned int)lapic_spurious_stub);
  198. /* Syscall gate (ring-3 can int 0x80). */
  199. set_idt_gate_user(0x80, (unsigned int)syscall_stub);
  200. /* Kernel-only voluntary reschedule gate (int 0x81). */
  201. set_idt_gate(0x81, (unsigned int)resched_stub);
  202. idtr.limit = (unsigned short)(sizeof(idt) - 1);
  203. idtr.base = (unsigned int)idt;
  204. __asm__ volatile ("lidt %0" : : "m"(idtr));
  205. /* Start the PIT at 1 kHz; schedule() drops it to 100 Hz while the BSP
  206. * is idle (see timer_set_hz). */
  207. timer_set_hz(1000);
  208. __asm__ volatile ("sti");
  209. }
  210. /* The BSP built the IDT once; APs only need to load the same pointer. */
  211. void idt_load_ap(void)
  212. {
  213. __asm__ volatile ("lidt %0" : : "m"(idtr));
  214. }
  215. extern unsigned char __bss_start[], __bss_end[];
  216. static int kworker_pid = -1;
  217. /* Parts of the system that must keep running independently of the WM:
  218. * input routing, thermal polling, cursor blink, kexec recovery, netlog
  219. * flushing, gfx-session cleanup and the shadow-buffer flush. */
  220. static void system_housekeeping(void)
  221. {
  222. process_reap_dead();
  223. thermal_housekeeping();
  224. mouse_poll_update();
  225. #ifndef NOWM
  226. wm_pump_keyboard();
  227. #endif
  228. netlog_flush();
  229. #ifndef NOWM
  230. wm_handle_kexec();
  231. init_server_supervise();
  232. wm_server_supervise();
  233. if (!wm_server_frame_active())
  234. vga_fb_flush_budget(VGA_FLUSH_BUDGET_BYTES);
  235. #else
  236. /* Diagnostic build: keep the direct-LFB boot console visible and do
  237. * not let the WM shadow flush overwrite it. */
  238. #endif
  239. }
  240. static void kworker_main(void)
  241. {
  242. for (;;) {
  243. system_housekeeping();
  244. process_sleep_ms(2);
  245. }
  246. }
  247. /* Idle is not a normal runnable task: schedule() selects it only when no
  248. * READY process exists. The kworker does the housekeeping; if it dies (or
  249. * could not be created), idle takes over as a degraded fallback. */
  250. static void kernel_idle_loop(void)
  251. {
  252. for (;;) {
  253. if (kworker_pid <= 0 ||
  254. !process_is_alive((unsigned int)kworker_pid)) {
  255. /* Idle must never sleep on the BKL: if a user process on
  256. * another CPU owns it, just keep idling and retry. */
  257. if (bkl_trylock()) {
  258. system_housekeeping();
  259. bkl_unlock();
  260. }
  261. }
  262. cpu_idle();
  263. }
  264. }
  265. /* Boot-stage tracing: COM1 (netlog mirrors it) plus the direct-LFB boot
  266. * console, so a machine without serial still shows where the boot stops. */
  267. static unsigned int boot_t0;
  268. static void boot_trace(const char *what)
  269. {
  270. unsigned int ms = get_ticks_ms() - boot_t0;
  271. bootcon_puts("[");
  272. bootcon_puts(what);
  273. bootcon_puts("] +");
  274. bootcon_dec(ms);
  275. bootcon_puts(" ms\n");
  276. serial_puts(SERIAL_COM1, "[boot] ");
  277. serial_puts(SERIAL_COM1, what);
  278. serial_puts(SERIAL_COM1, " +");
  279. serial_putdec(SERIAL_COM1, ms);
  280. serial_puts(SERIAL_COM1, " ms\n");
  281. }
  282. static void boot_val(const char *name, unsigned int v)
  283. {
  284. bootcon_puts(name);
  285. bootcon_puts(": ");
  286. bootcon_dec(v);
  287. bootcon_puts("\n");
  288. serial_puts(SERIAL_COM1, name);
  289. serial_puts(SERIAL_COM1, ": ");
  290. serial_putdec(SERIAL_COM1, v);
  291. serial_puts(SERIAL_COM1, "\n");
  292. }
  293. /* Bounded PIT self-test. If the 8259 does not deliver IRQ0, every later
  294. * delay/timeout would spin on a frozen tick counter; say so and stop. */
  295. static int pit_ticking(void)
  296. {
  297. unsigned int t0 = get_ticks_ms();
  298. unsigned int n;
  299. for (n = 0; n < 5000000u; n++) {
  300. if (get_ticks_ms() != t0)
  301. return 1;
  302. __asm__ volatile ("pause");
  303. }
  304. return 0;
  305. }
  306. /* A kexec/net-dev reload starts a fresh kernel with zeroed BSS, so the
  307. * leased address and resolver would otherwise fall back to the static
  308. * default until someone types dhcp. The previous kernel stashed them in
  309. * the boot-info reserved words; apply them before the boot DHCP attempt. */
  310. static int net_restore_boot_config(void)
  311. {
  312. const volatile unsigned int *p;
  313. unsigned char ip[4], mask[4], gw[4], dns[4];
  314. unsigned int i;
  315. if (!bootinfo_valid() || !(bootinfo_flags() & BOOTINFO_FLAG_NET))
  316. return 0;
  317. p = bootinfo_words();
  318. for (i = 0; i < 4; i++) {
  319. ip[i] = (unsigned char)(p[7] >> (8 * i));
  320. mask[i] = (unsigned char)(p[8] >> (8 * i));
  321. gw[i] = (unsigned char)(p[9] >> (8 * i));
  322. dns[i] = (unsigned char)(p[10] >> (8 * i));
  323. }
  324. if (!(ip[0] || ip[1] || ip[2] || ip[3]))
  325. return 0;
  326. net_configure(ip, mask, gw);
  327. if (dns[0] || dns[1] || dns[2] || dns[3])
  328. net_set_dns(dns);
  329. boot_trace("net retained");
  330. /* A resolver is what net-dev users notice missing; without one, let
  331. * the boot DHCP attempt learn it. */
  332. return dns[0] || dns[1] || dns[2] || dns[3];
  333. }
  334. /* Saved WiFi networks on the writable /data volume: let the normal
  335. * supplicant scan and join any known network in the background. It leaves a
  336. * wired link that is physically up alone, and a missing /data or wifi helper
  337. * is harmless. */
  338. static void boot_wifi_autoconnect(void)
  339. {
  340. unsigned int sz = 0;
  341. int is_dir = 0;
  342. if (vfs_stat(WIFI_CRED_PATH, &sz, &is_dir) == 0 &&
  343. !is_dir && sz > 0) {
  344. struct vfs_file f;
  345. struct vfs_mount *m = 0;
  346. if (vfs_load_file("/ramfs/bin/wifi", &f, &m) == 0) {
  347. /* The bootscan thread exits right after starting
  348. * this helper, so it must be detached (parent 0). */
  349. if (process_create_user_full("wifi", f.data, f.size,
  350. "autoconnect", "/", 0, 0,
  351. 0) > 0)
  352. serial_puts(SERIAL_COM1,
  353. "wifi: autoconnect started\n");
  354. vfs_release_file(m, &f);
  355. }
  356. }
  357. }
  358. /* Boot-time storage scan in its own kernel thread. A process (unlike the
  359. * idle context kernel_main runs in) may sleep, so the probes' long waits
  360. * (floppy motor, ATA/AHCI timeouts) go through vfs_scan_relax() and the WM
  361. * and the first terminal run meanwhile. Disk file operations wait for
  362. * vfs_scan_busy; /ramfs and /share do not. The WiFi autoconnect needs
  363. * /data, so it runs here after the mount. Every COM1 character this thread
  364. * writes is also captured into the bootcon scan ring, which the ring-3
  365. * `bootscan` window tails live (it is spawned before the first terminal). */
  366. static volatile int boot_dhcp_done;
  367. static void boot_storage_main(void)
  368. {
  369. bootcon_scan_begin();
  370. vfs_mount_all(1);
  371. sys_mount_load_config();
  372. boot_trace("storage");
  373. /* USB storage can NAK its first read for seconds while a card reader or
  374. * stick initialises. Close the live scan first, then mount it behind
  375. * the usable desktop; the boot window no longer waits for it. */
  376. bootcon_scan_end();
  377. vfs_mount_usb();
  378. sys_mount_load_config();
  379. /* As before, WiFi only starts after the boot DHCP attempt on the
  380. * wired NIC, so two DHCP clients never overlap. */
  381. while (!boot_dhcp_done)
  382. process_sleep_ms(20);
  383. boot_wifi_autoconnect();
  384. boot_trace("wifi auto");
  385. }
  386. void kernel_main(void);
  387. void kernel_main(void)
  388. {
  389. unsigned char *p = __bss_start;
  390. int net_kept, storage_inline;
  391. while (p < __bss_end)
  392. *p++ = 0;
  393. /* Earliest possible output: straight into the boot framebuffer, before
  394. * paging, drivers, the heap or the serial port. Everything below logs
  395. * here as well as to COM1, so a machine without serial (the X201) can
  396. * show where the boot stops. */
  397. bootcon_init();
  398. bootcon_puts(OS_NAME " v" OS_VERSION "\n");
  399. serial_init(SERIAL_COM1);
  400. serial_ring_init();
  401. /* Network console mirror from the very first line on; the ring holds the
  402. * early boot output until the WM loop starts flushing it. */
  403. netlog_init();
  404. serial_puts(SERIAL_COM1, "\n" OS_NAME " v" OS_VERSION " booted\n");
  405. boot_trace("start");
  406. /* GDT/TSS and the per-CPU GS base must exist before anything that can
  407. * use current_proc()/this_cpu(). The BSS is already cleared and the
  408. * GDT/TSS live at identity-mapped addresses. */
  409. gdt_tss_init(0);
  410. boot_trace("gdt");
  411. mm_init();
  412. mm_dump();
  413. boot_trace("mm");
  414. boot_val("mm free KB", mm_free_pages() * 4);
  415. kmalloc_init();
  416. /* Report the VBE geometry before paging, so a boot that dies in the
  417. * translation switch still says which mode the BIOS picked. */
  418. bootcon_fb_info();
  419. paging_init();
  420. boot_trace("paging");
  421. /* Keep a RAM copy of the boot console text; the WM hides the
  422. * framebuffer console later and this is what `bootlog` prints. */
  423. bootcon_log_init();
  424. /* paging_init only ORs in PSE; make sure the BSP's SSE state is on
  425. * before any drawing path can select an SSE2 helper. */
  426. cpu_enable_sse();
  427. cpu_init_fpu();
  428. /* ACPI needs paging for table access; a missing or unusable MADT simply
  429. * leaves the machine at one CPU. */
  430. acpi_init();
  431. acpi_dump();
  432. /* The kernel keeps the 8259 on LAPIC LINT0; firmware-left IOAPIC
  433. * entries would otherwise deliver into the PIC/LAPIC vector space. */
  434. ioapic_mask_all();
  435. boot_trace("acpi");
  436. boot_val("acpi cpus", acpi_cpu_count());
  437. io_init();
  438. boot_trace("io");
  439. /* P-states/deep C-states first: idle_init() picks its default from
  440. * the power module (deep MWAIT on Nehalem, HLT elsewhere). */
  441. power_init();
  442. idle_init();
  443. boot_trace("power");
  444. thermal_init();
  445. boot_trace("thermal");
  446. /* Board sensors: the ThinkPad EC probe is gated on SMBIOS identifying a
  447. * Lenovo/IBM machine, so it is a no-op everywhere else. The Chrome EC
  448. * probe is skipped when the ThinkPad EC was found. */
  449. tpec_init();
  450. cros_ec_init();
  451. boot_trace("ec");
  452. /* process_init must run before timer_init: once the PIT is started (sti
  453. * in timer_init) the context-switch stub runs on every tick and reads
  454. * the current process, its CR3 and the TSS, so those must be valid. */
  455. process_init();
  456. boot_trace("process");
  457. timer_init();
  458. boot_t0 = get_ticks_ms();
  459. boot_trace("timer");
  460. if (!pit_ticking()) {
  461. bootcon_puts("*** PIT NOT TICKING ***\n");
  462. serial_puts(SERIAL_COM1, "*** PIT NOT TICKING ***\n");
  463. for (;;)
  464. __asm__ volatile ("cli; hlt");
  465. }
  466. boot_val("timer ticks", get_ticks_ms());
  467. /* The PIT (and its sti) is live, so the AP bring-up can use it as a
  468. * timeout clock. APs idle until smp_enable_sched() after boot. */
  469. smp_init();
  470. boot_trace("smp");
  471. boot_val("smp cpus", cpu_count);
  472. mouse_init();
  473. boot_trace("ps2");
  474. vga_shadow_init();
  475. vga_fb_flush();
  476. boot_trace("vga");
  477. /* The command pack: read-only, mounted at /ramfs (see ramfs.c). The
  478. * boot path copied it into RAM (the legacy stage's low gap, the UEFI
  479. * loader or kexec); ramfs_init takes its own copy so the boot region
  480. * can be released. The mount is created even without a pack, so a running
  481. * board can be recovered with `make cmds-dev`/`make net-cmds`. */
  482. {
  483. unsigned int pack_addr = bootinfo_pack_addr();
  484. unsigned int pack_len = bootinfo_pack_size();
  485. int ok = 0, gz = 0;
  486. if (!pack_addr || !pack_len)
  487. serial_puts(SERIAL_COM1, "ramfs: no boot pack\n");
  488. else {
  489. const unsigned char *p = (const unsigned char *)pack_addr;
  490. gz = pack_len >= 2 && p[0] == 0x1F && p[1] == 0x8B;
  491. serial_puts(SERIAL_COM1, "ramfs: boot pack at ");
  492. serial_puthex(SERIAL_COM1, pack_addr);
  493. serial_puts(SERIAL_COM1, ", ");
  494. serial_putdec(SERIAL_COM1, pack_len);
  495. serial_puts(SERIAL_COM1, gz ? " bytes (gzip)\n" :
  496. " bytes\n");
  497. if (gz)
  498. ramfs_set_boot_image((const void *)pack_addr,
  499. pack_len, 1);
  500. ok = ramfs_init((const void *)pack_addr, pack_len) == 0;
  501. if (!ok) {
  502. serial_puts(SERIAL_COM1, "ramfs: bad boot pack\n");
  503. ramfs_set_boot_image(0, 0, 0);
  504. mm_free_range(pack_addr, pack_len);
  505. } else {
  506. serial_puts(SERIAL_COM1, "ramfs: pack ok, ");
  507. serial_putdec(SERIAL_COM1, ramfs_count());
  508. serial_puts(SERIAL_COM1, " files, ");
  509. serial_putdec(SERIAL_COM1, ramfs_pack_size());
  510. serial_puts(SERIAL_COM1, " bytes\n");
  511. cursor_load();
  512. if (!gz) {
  513. /* ramfs has its own copy now; keep that
  514. * as the self-update image. */
  515. ramfs_set_boot_image(ramfs_pack_base(),
  516. ramfs_pack_size(), 0);
  517. mm_free_range(pack_addr, pack_len);
  518. }
  519. /* A gzip boot image stays reserved so
  520. * `install self` can write it to P2. */
  521. }
  522. }
  523. (void)ok;
  524. vfs_mount_ramfs();
  525. /* /share too: the WM and the first terminal may use it while the
  526. * bootscan thread is still probing the disks, and a path that
  527. * does not resolve yet would wait for the whole scan. */
  528. vfs_mount_share();
  529. }
  530. boot_trace("ramfs");
  531. boot_val("ramfs files", ramfs_count());
  532. #ifndef NOWM
  533. /* Hand the userland over to PID 1 before touching disks. Init starts
  534. * the WM and the services; if /ramfs/bin/init is absent there is no WM
  535. * and the boot console stays visible. */
  536. wm_server_init();
  537. boot_trace("wm init");
  538. init_server_start();
  539. boot_trace("init");
  540. #else
  541. /* Diagnostic build: boot to the console, no WM, no terminal. */
  542. bootcon_puts("WM disabled (diagnostic build)\n");
  543. serial_puts(SERIAL_COM1, "nowm: window manager disabled\n");
  544. boot_trace("wm off");
  545. #endif
  546. /* Publish the storage scan before anything can run a command: disk
  547. * paths wait for vfs_scan_busy (owned by the idle context until the
  548. * bootscan thread's vfs_mount_all() takes it over), /ramfs and /share
  549. * do not. Then let the WM spawn the bootscan window and the first
  550. * terminal at once; neither it nor the WM needs the NIC probe or the
  551. * disks below. */
  552. vfs_scan_owner_pid = 0;
  553. vfs_scan_busy = 1;
  554. #ifndef NOWM
  555. wm_server_boot_ready();
  556. boot_trace("terminal ready");
  557. #else
  558. boot_trace("terminal off");
  559. #endif
  560. #ifndef NOWM
  561. /* Let the WM put the bootscan log window and the first terminal on
  562. * screen before the USB bring-up below: kernel_main is the idle
  563. * context, so halting here hands the CPU to the WM and those windows.
  564. * Bounded, in case no terminal ever presents. */
  565. {
  566. unsigned int t0 = get_ticks_ms();
  567. while (!wm_first_window_presented &&
  568. get_ticks_ms() - t0 < 1000)
  569. __asm__ volatile ("sti; hlt");
  570. }
  571. boot_trace("terminal shown");
  572. #endif
  573. /* USB HID backend (mouse + keyboard) and the USB device drivers:
  574. * controller bring-up + first scan; devices plugged in later are
  575. * picked up by the hotplug watcher. Non-preemptible, exactly like
  576. * the bring-up before the WM existed: port resets and the SOF a
  577. * freshly enabled low-speed device needs within 3 ms must not wait
  578. * for a WM frame. Before the NIC probe: ASIX/RNDIS/RTL8821AU bind
  579. * during this scan, and USB disks before the bootscan thread. */
  580. asix_register();
  581. usbmsc_register();
  582. rtl8821au_register();
  583. rndis_register();
  584. preempt_disable();
  585. usbhid_init();
  586. preempt_enable();
  587. boot_trace("usb");
  588. /* Probe the NIC (link negotiation is asynchronous now) before the
  589. * kworker starts, so its netlog flushes have a device to use. */
  590. netdev_active();
  591. net_kept = net_restore_boot_config();
  592. boot_trace("net");
  593. /* The idle process is the kernel_main context; housekeeping runs in
  594. * its own process so it cannot be starved by a busy system. */
  595. kworker_pid = process_create("kworker", kworker_main);
  596. if (kworker_pid < 0) {
  597. serial_puts(SERIAL_COM1, "kworker: cannot create, using idle fallback\n");
  598. kworker_pid = -1;
  599. } else {
  600. process_set_weight((unsigned int)kworker_pid, 4);
  601. process_set_affinity((unsigned int)kworker_pid, 1);
  602. }
  603. boot_trace("kworker");
  604. /* Slow storage bring-up happens behind the usable desktop, in a
  605. * thread that may sleep through its probe timeouts. The scan was
  606. * published above; its vfs_mount_all() takes over the ownership.
  607. * Without a thread slot, scan inline as before. */
  608. boot_trace("storage begin");
  609. storage_inline = 0;
  610. if (process_create("bootscan", boot_storage_main) <= 0) {
  611. vfs_mount_all(0);
  612. boot_trace("storage");
  613. storage_inline = 1;
  614. }
  615. /* With a linked NIC present, try DHCP; on failure the static default
  616. * stays. A wired NIC without a cable is skipped so the WiFi fallback
  617. * below does not have to wait out the 4 s timeout first. Deliberately
  618. * after the WM: a missing cable or DHCP server must not delay the first
  619. * frame. */
  620. {
  621. const struct netdev *nd = netdev_active();
  622. int linked = nd && netdev_link(nd);
  623. if (linked && !net_kept)
  624. dhcp_run(4000);
  625. boot_trace(net_kept ? "dhcp skipped" :
  626. (linked ? "dhcp" : "dhcp no link"));
  627. }
  628. boot_dhcp_done = 1;
  629. if (storage_inline) {
  630. boot_wifi_autoconnect();
  631. boot_trace("wifi auto");
  632. }
  633. /* Dump the active NIC's counters after the boot DHCP attempt. With
  634. * the ASIX as the management link this appears in netmon even when
  635. * the active e1000e cannot pass traffic. */
  636. {
  637. const struct netdev *nd = netdev_active();
  638. if (nd && (nd->dump_brief || nd->dump_regs)) {
  639. io_putstr("\n[boot netregs: ");
  640. io_putstr(nd->name);
  641. io_putstr("]\n");
  642. if (nd->dump_brief)
  643. nd->dump_brief();
  644. else
  645. nd->dump_regs();
  646. }
  647. }
  648. /* Boot-time device/FS setup is complete; APs may now take user work.
  649. * Kernel threads stay pinned to the BSP and serialize on the BKL. */
  650. smp_enable_sched();
  651. boot_trace("sched");
  652. kernel_idle_loop();
  653. }