Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/native/kernel/x86/kmain_x86.c # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / native / kernel / x86 / kmain_x86.c` 2609 lines ยท 111754 bytes Raw Blame History 1 /* SPDX-License-Identifier: Apache-2.0 2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 /* kmain_x86.c -- AIENOS-KERNEL-0: the C kernel core on x86_64, first 18 * cut, for the 2017 iMac (iMac18,3, Core i5-7500) and QEMU q35. 19 * 20 * After ExitBootServices (efi_x86.c) on the firmware's page tables: 21 * interrupts off, own GDT + TSS (IST1 stack for #DF, NMI, #MC) and IDT (256 22 * stubs, trap.S), the CHANDOF3 record checked (core/handoff_check.c), a frame 23 * allocator over the memory map (mm/frames.c), own 4-level page tables that 24 * identity map [0, top) with 2 MiB pages (RAM write-back, the rest uncached, 25 * the GOP framebuffer write-combining through PAT entry 1) and a 4 KiB guard 26 * page under the kernel stack, CR3 switched and the stack moved. W^X (#409): 27 * EFER.NXE and CR0.WP on every core, the image's code read-only executable, 28 * its read-only data read-only no-execute, everything else (data, bss, 29 * stacks, heap, MMIO, framebuffer) no-execute; probes and an audit of every 30 * leaf prove it. W^X is not process isolation. Then: the 31 * screen console (core/fbcon.c), heap (mm/heap.c), the guard page proven to 32 * fault and the fault contained, the TSC measured against the HPET, the 33 * local APIC (xAPIC) with its timer at 100 Hz for 20 ticks, the MADT CPU 34 * count, the secondary cores started and parked (smp_x86.S), the AHCI and 35 * NVMe disks read-only and a look at the Ethernet chip (pci_x86.c, 36 * ahci_x86.c), and the final report. With a keyboard, Allen's window, whose 37 * memory lives in its own partition of the approved hard disk (memory_x86.c, 38 * the only disk writes). Goodbye, a tap of the power button (PM1 status, 39 * polled) or CK_X86_IDLE_S without a key rests the computer: the picture goes 40 * to black (ui/allen_ui.c), then the known display controller is asked to 41 * switch the panel off (panel_x86.c). Only a register-confirmed off permits 42 * reversible rest with any-key wake. Unsupported or failed panel control 43 * uses the existing ACPI S5 power-off instead, with no automatic restart. 44 * Without a keyboard it holds the screen CK_X86_HOLD_S seconds and 45 * powers off through ACPI S5 (FADT PM1 control + the DSDT's \_S5 package); the lab image 46 * (CK_X86_REPORT=1) without a keyboard restarts through the FADT reset register instead, back 47 * into its network loader (native/boot/net_loader.c). 48 * Scheduling on the secondary cores, the network driver and VT-d 49 * are later cuts. No runtime service 50 * is called. QEMU runs of this path qualify nothing physical. */ 51 #include "../core/ck_internal.h" 52 #include "../core/handoff_check.h" 53 #include "../core/spinlock.h" 54 #include "../mm/frames.h" 55 #include "../mm/heap.h" 56 #include "../svc/allen_code.h" 57 #include "../dev/usb_hid.h" 58 #include "../svc/allen_intent.h" 59 #include "../svc/allen_reply.h" 60 #include "../svc/courier.h" 61 #include "courier_udp.h" 62 #include "../ui/allen_ui.h" 63 #include "x86.h" 64 #include "../../boot/netboot_proto.h" 65 #include "swap_x86.h" 66 #include "bench_x86.h" 67 #include "local_tools.h" 68 #include "local_wire.h" 69 70 #ifndef AIENOS_COMMIT 71 #define AIENOS_COMMIT "unknown" 72 #endif 73 #ifndef CK_X86_REPORT 74 #define CK_X86_REPORT 0 /* 1 only in the opt-in lab image: the network report */ 75 #endif 76 #ifndef CK_X86_HOLD_S 77 #define CK_X86_HOLD_S 60u 78 #endif 79 #ifndef CK_X86_IDLE_S 80 #define CK_X86_IDLE_S 600u /* Allen's window: the computer rests after this long without a key (0: never) */ 81 #endif 82 83 #define SEL_CODE 0x08 84 #define SEL_DATA 0x10 85 #define SEL_TSS 0x18 86 #define VEC_TIMER 0x40 87 #define VEC_TLB_PROBE 0x50 /* the shootdown self-test's probe on a secondary core */ 88 #define VEC_TLB 0xf0 /* TLB shootdown: flush tlb_va on this core and acknowledge */ 89 #define VEC_SPURIOUS 0xff 90 #define STACK_BYTES (64u << 10) 91 #define IST_BYTES (16u << 10) 92 #define HEAP_PAGES 256u /* 1 MiB */ 93 #define MAP_TOP_MAX (512ull << 30) /* one PML4 entry */ 94 95 #define PTE_P 0x1ull 96 #define PTE_W 0x2ull 97 #define PTE_PWT 0x8ull 98 #define PTE_PCD 0x10ull 99 #define PTE_PS 0x80ull 100 #define PTE_ADDR 0x000ffffffffff000ull 101 #define MSR_EFER 0xc0000080u 102 #define EFER_NXE (1ull << 11) 103 #define CR0_WP (1ull << 16) 104 105 /* W^X negative controls (make IMACKERN_WX_MUTANT=..., QEMU only, never 106 * deployed): no_nx drops every NX bit, text_writable leaves the code 107 * writable, ap_no_wp starts the secondary cores without CR0.WP (smp_x86.S), 108 * no_shootdown leaves the other cores' TLBs stale (invlpg on the boot core 109 * only). The W^X and TLB probes or the wx_audit core count below must then fail. */ 110 #define PTE_XD (1ull << 63) /* the hardware execute-disable bit */ 111 #ifdef CK_X86_WX_MUTANT_NO_NX 112 #define PTE_NX 0ull 113 #else 114 #define PTE_NX PTE_XD 115 #endif 116 #ifdef CK_X86_WX_MUTANT_TEXT_RW 117 #define TEXT_W PTE_W 118 #else 119 #define TEXT_W 0ull 120 #endif 121 122 /* image_x86_64.ld, runtime addresses: [image_base, text_start) PE header, 123 * [text_start, text_end) code, [ro_start, ro_end) rodata/relocs/GOT, then 124 * data and bss up to image_end. All page aligned. */ 125 extern char __image_base[], __text_start[], __text_end[], __ro_start[], __ro_end[], __image_end[]; 126 127 const char *ck_commit(void) { return AIENOS_COMMIT; } 128 129 static struct ck_handoff *hand; 130 static struct ck_frames frames; 131 static struct ck_heap heap; 132 static uint64_t tramp_pa; /* secondary-core trampoline page, below 1 MiB; 0 = none */ 133 134 /* ---- descriptor tables ---- */ 135 struct __attribute__((packed)) tss64 { 136 uint32_t r0; 137 uint64_t rsp[3]; 138 uint64_t r1; 139 uint64_t ist[7]; 140 uint64_t r2; 141 uint16_t r3, iomap; 142 }; 143 _Static_assert(sizeof(struct tss64) == 104, "tss64 size"); 144 struct __attribute__((packed)) dtr { 145 uint16_t limit; 146 uint64_t base; 147 }; 148 struct idt_gate { 149 uint16_t off0, sel; 150 uint8_t ist, attr; 151 uint16_t off1; 152 uint32_t off2, zero; 153 }; 154 _Static_assert(sizeof(struct idt_gate) == 16, "idt gate size"); 155 156 static uint64_t gdt[7] __attribute__((aligned(16))); 157 static struct tss64 tss __attribute__((aligned(16))); 158 static struct idt_gate idt[256] __attribute__((aligned(16))); 159 static uint8_t ist_stack[IST_BYTES] __attribute__((aligned(16))); 160 /* First page: the guard, unmapped once the kernel's tables are live. */ 161 static uint8_t kstack[4096 + STACK_BYTES] __attribute__((aligned(4096))); 162 163 static void tables_load(void) 164 { 165 gdt[0] = 0; 166 gdt[1] = 0x00209a0000000000ull; /* 64-bit code, DPL 0 */ 167 gdt[2] = 0x0000920000000000ull; /* data */ 168 uint64_t tb = (uint64_t)(uintptr_t)&tss, tl = sizeof tss - 1; 169 gdt[3] = (tl & 0xffff) | (tb & 0xffffff) << 16 | 0x89ull << 40 | ((tl >> 16) & 0xf) << 48 | 170 ((tb >> 24) & 0xff) << 56; 171 gdt[4] = tb >> 32; 172 gdt[5] = 0x0020fa0000000000ull; /* CPL3 64-bit code, selector 0x2b */ 173 gdt[6] = 0x0000f20000000000ull; /* CPL3 data, selector 0x33 */ 174 tss.ist[0] = (uint64_t)(uintptr_t)(ist_stack + sizeof ist_stack); 175 tss.iomap = sizeof tss; 176 struct dtr g = {sizeof gdt - 1, (uint64_t)(uintptr_t)gdt}; 177 ck_x86_load_gdt(&g, SEL_CODE, SEL_DATA, SEL_TSS); 178 179 for (unsigned v = 0; v < 256; v++) { 180 uint64_t a = (uint64_t)(uintptr_t)ck_x86_isr_stubs + (uint64_t)v * CK_X86_ISR_STRIDE; 181 idt[v].off0 = (uint16_t)a; 182 idt[v].sel = SEL_CODE; 183 idt[v].ist = (v == 2 || v == 8 || v == 18) ? 1 : 0; 184 idt[v].attr = v == 0x80 ? 0xee : 0x8e; /* present, DPL 0, 64-bit interrupt gate */ 185 idt[v].off1 = (uint16_t)(a >> 16); 186 idt[v].off2 = (uint32_t)(a >> 32); 187 idt[v].zero = 0; 188 } 189 struct dtr i = {sizeof idt - 1, (uint64_t)(uintptr_t)idt}; 190 __asm__ volatile("lidt %0" ::"m"(i) : "memory"); 191 } 192 193 /* ---- power ---- */ 194 static uint64_t tsc_hz; 195 uint64_t ck_x86_tsc_hz(void) { return tsc_hz; } 196 197 static void delay_ms(uint64_t ms) 198 { 199 if (!tsc_hz) 200 return; 201 uint64_t t0 = ck_rdtsc(), n = tsc_hz / 1000 * ms; 202 while (ck_rdtsc() - t0 < n) 203 ck_pause(); 204 } 205 206 /* \_S5 sleep types from the DSDT: "_S5_" PackageOp PkgLength NumElements 207 * then two integers (ZeroOp, OneOp, OnesOp or BytePrefix n). */ 208 static int s5_types(const uint8_t *dsdt, uint32_t len, unsigned *a, unsigned *b) 209 { 210 for (uint32_t i = 36; i + 12 < len; i++) { 211 if (memcmp(dsdt + i, "_S5_", 4) != 0 || dsdt[i + 4] != 0x12) 212 continue; 213 uint32_t p = i + 5; 214 p += 1u + (dsdt[p] >> 6); /* PkgLength: lead byte + follow bytes */ 215 p++; /* NumElements */ 216 unsigned v[2]; 217 for (unsigned k = 0; k < 2; k++) { 218 if (p >= len) 219 return -1; 220 uint8_t op = dsdt[p++]; 221 if (op == 0x00 || op == 0x01) 222 v[k] = op; 223 else if (op == 0xff) 224 v[k] = 0x7; 225 else if (op == 0x0a && p < len) 226 v[k] = dsdt[p++] & 7u; 227 else 228 return -1; 229 } 230 *a = v[0]; 231 *b = v[1]; 232 return 0; 233 } 234 return -1; 235 } 236 237 static uint32_t rd32(const void *p, unsigned off) 238 { 239 uint32_t v; 240 memcpy(&v, (const uint8_t *)p + off, 4); 241 return v; 242 } 243 static uint64_t rd64(const void *p, unsigned off) 244 { 245 uint64_t v; 246 memcpy(&v, (const uint8_t *)p + off, 8); 247 return v; 248 } 249 250 static void acpi_poweroff(void) 251 { 252 const uint8_t *fadt = hand && hand->rsdp ? ck_acpi_lookup(hand->rsdp, "FACP") : 0; 253 if (!fadt) { 254 ck_puts("power: no FADT\n"); 255 return; 256 } 257 uint32_t flen = rd32(fadt, 4); 258 uint64_t dsdt = flen >= 148 ? rd64(fadt, 140) : 0; 259 if (!dsdt) 260 dsdt = rd32(fadt, 40); 261 uint32_t pm1a = rd32(fadt, 64), pm1b = rd32(fadt, 68), smi = rd32(fadt, 48); 262 uint8_t enable = fadt[52]; 263 unsigned ta, tb; 264 if (!dsdt || s5_types((const uint8_t *)(uintptr_t)dsdt, rd32((const void *)(uintptr_t)dsdt, 4), &ta, &tb)) { 265 ck_puts("power: no \\_S5 package in the DSDT\n"); 266 return; 267 } 268 if (!pm1a || pm1a > 0xffff) { 269 ck_printf("power: PM1a control block 0x%x is not an I/O port\n", pm1a); 270 return; 271 } 272 if (!(ck_inw((uint16_t)pm1a) & 1) && smi && enable) { /* SCI_EN clear: ACPI mode off */ 273 ck_outb((uint16_t)smi, enable); 274 for (unsigned i = 0; i < 300 && !(ck_inw((uint16_t)pm1a) & 1); i++) 275 delay_ms(10); 276 } 277 ck_printf("power: off via ACPI S5 pm1a=0x%x pm1b=0x%x slp_typ=%u/%u\n", pm1a, pm1b, ta, tb); 278 ck_outw((uint16_t)pm1a, (uint16_t)(ta << 10 | 1u << 13)); 279 if (pm1b && pm1b <= 0xffff) 280 ck_outw((uint16_t)pm1b, (uint16_t)(tb << 10 | 1u << 13)); 281 delay_ms(2000); 282 ck_puts("power: still running after the S5 write\n"); 283 } 284 285 #if CK_X86_REPORT 286 /* Lab image only: restart instead of powering off, so the iMac comes back to 287 * its network loader (NETLDR.EFI) for the next test without a hand on the 288 * power button. The FADT reset register (ACPI 6.5 section 4.8.3.6; on the 289 * iMac18,3: flags bit 10 RESET_REG_SUP set, SystemIO port 0xCF9, value 0x06, 290 * read from its FACP table on 2026-10-17); without one, the same write to the 291 * PCH reset control port 0xCF9 that the FADT names. */ 292 static void acpi_reset(void) 293 { 294 const uint8_t *fadt = hand && hand->rsdp ? ck_acpi_lookup(hand->rsdp, "FACP") : 0; 295 uint16_t port = 0xCF9; 296 uint8_t value = 0x06; 297 if (fadt && rd32(fadt, 4) >= 129 && (rd32(fadt, 112) & (1u << 10)) && fadt[116] == 1 /* SystemIO */ && 298 rd64(fadt, 120) && rd64(fadt, 120) <= 0xffff) { 299 port = (uint16_t)rd64(fadt, 120); 300 value = fadt[128]; 301 ck_printf("power: restart via the ACPI reset register port=0x%x value=0x%x\n", port, value); 302 } else { 303 ck_puts("power: restart via port 0xcf9 (no usable ACPI reset register)\n"); 304 } 305 ck_outb(port, value); 306 for (volatile uint64_t i = 0; i < 100000000ull; i++) 307 __asm__ volatile("pause"); 308 ck_puts("power: still running after the reset write\n"); 309 } 310 #endif 311 312 /* Allen on the screen (ui/allen_ui.c) with its first local answers 313 * (svc/allen_reply.c). Every Enter gets an answer on the console 314 * ("allen: ..."); when a keyboard is ready and the RAM for drawing is there, 315 * the screen switches from the boot report to Allen's window, which stays 316 * up (no countdown to power-off). "goodbye", a tap of the power button or 317 * CK_X86_IDLE_S without a key fades the picture to black, then tries the 318 * existing guarded AMD panel-off sequence. Confirmed off rests the cores; 319 * any key or another tap restores the panel before the picture. If the 320 * controller cannot confirm off (or restore it), ACPI S5 is the fallback, 321 * not black pixels with a lit backlight. No keyboard keeps the timed hold. */ 322 static int allen_on; 323 static uint64_t allen_bye; /* TSC when Allen said goodbye; 0 = still talking */ 324 static uint64_t allen_woke; /* TSC when Allen's window took the screen */ 325 static uint64_t allen_key; /* TSC of the last key, or of waking; the idle timer counts from it */ 326 static int allen_asleep; /* rest requested: fade pending, then confirmed panel off or S5 */ 327 static uint64_t panel_due; /* TSC when the rest began: the panel goes off once the picture is black (0: not waiting) */ 328 #define PANEL_WAIT_S 10u /* the picture gets this long to go black before the panel goes off anyway */ 329 static int panel_dark; /* panel_off succeeded; waking must restore it */ 330 static uint16_t pm1_sts; /* PM1a status port (FADT), 0 = no power-button watch */ 331 static uint64_t pwr_last; /* TSC of the last power-button tap taken */ 332 333 /* The power button sets PWRBTN_STS (PM1 status bit 8, write 1 to clear) whether or 334 * not it is enabled as an interrupt (chipset book 332691 p163). The enable bit is 335 * cleared so no SMI or SCI goes to the firmware while we poll; holding the button 336 * 4 s is still the chipset's own hard power-off. */ 337 static void power_button_watch(void) 338 { 339 const uint8_t *fadt = hand && hand->rsdp ? ck_acpi_lookup(hand->rsdp, "FACP") : 0; 340 if (!fadt || rd32(fadt, 4) < 92) { 341 ck_puts("power: no FADT; the power button is not watched\n"); 342 return; 343 } 344 uint32_t evt = rd32(fadt, 56); /* PM1a_EVT_BLK */ 345 uint8_t len = fadt[88]; /* PM1_EVT_LEN: status then enable, len/2 each */ 346 if (!evt || evt > 0xffff || len < 4) { 347 ck_printf("power: PM1a event block 0x%x (%u bytes) is not a watchable I/O port\n", evt, len); 348 return; 349 } 350 /* Real chipsets latch PWRBTN_STS whether or not PWRBTN_EN is set (ACPI 6.5 351 * 4.8.2.2.1.2: "unconditionally set"), and with it clear a press raises no SMI# 352 * or SCI (332691 PM1_EN). QEMU's model (hw/acpi/core.c acpi_pm1_evt_power_down) 353 * latches only when PWRBTN_EN is set; interrupts are off here, so under a 354 * hypervisor the bit is set instead and the SCI line it raises goes nowhere. */ 355 uint32_t r[4]; 356 ck_cpuid(1, 0, r); 357 int hv = (r[2] >> 31) & 1; 358 uint16_t en = (uint16_t)(evt + len / 2); 359 uint16_t env = (uint16_t)(ck_inw(en) & ~0x100u); 360 if (hv) 361 env |= 0x100; 362 ck_outw(en, env); 363 ck_outw((uint16_t)evt, 0x100); /* a press from before now is forgotten */ 364 pm1_sts = (uint16_t)evt; 365 ck_printf("power: button watched at PM1 status port 0x%x (tap: sleep or wake; hold 4 s: off%s)\n", evt, 366 hv ? "; enable bit set for the hypervisor's chipset model" : ""); 367 } 368 static int power_button_tapped(void) 369 { 370 if (!pm1_sts || !(ck_inw(pm1_sts) & 0x100)) 371 return 0; 372 ck_outw(pm1_sts, 0x100); 373 uint64_t now = ck_rdtsc(); 374 if (now - pwr_last < tsc_hz / 2) /* bounce */ 375 return 0; 376 pwr_last = now; 377 return 1; 378 } 379 /* Resting while Allen sleeps. Nothing on the screen moves then, so the 380 * drawing cores wait in MWAIT on park.gen until a write to it (Allen waking, 381 * or draw_stop) instead of spinning; the boot core, which still polls the 382 * keyboard and the power button, halts between polls until a one-shot LAPIC 383 * timer interrupt REST_MS later. The MWAIT hint is the deepest of C6, C3 and 384 * C1 that CPUID leaf 5 lists (an MWAIT C-state the firmware limits is entered 385 * as a shallower one). Without MONITOR/MWAIT the drawing cores spin as before 386 * and the boot core uses HLT. */ 387 #define REST_MS 20u 388 static struct { 389 volatile uint32_t gen; 390 uint8_t pad[60]; /* alone on its 64-byte line: only a wake writes it */ 391 } park __attribute__((aligned(64))); 392 static int rest_mwait; 393 static uint32_t rest_hint, lapic_per_ms; 394 395 static void rest_probe(uint32_t lapic_hz) 396 { 397 uint32_t r[4]; 398 lapic_per_ms = lapic_hz / 1000u; 399 ck_cpuid(0, 0, r); 400 uint32_t max = r[0]; 401 ck_cpuid(1, 0, r); 402 if (max < 5 || !(r[2] & 1u << 3)) 403 return; 404 ck_cpuid(5, 0, r); /* EDX: 4 bits of sub-states per MWAIT C-state, C0 first; hint (n - 1) << 4 for Cn */ 405 rest_mwait = 1; 406 rest_hint = (r[3] >> 12 & 0xfu) ? 0x20u : (r[3] >> 8 & 0xfu) ? 0x10u : 0x00u; 407 } 408 409 /* A drawing core while the screen is dark: waits until park.gen is no longer g. */ 410 static void rest_wait(uint32_t g) 411 { 412 if (!rest_mwait) { 413 ck_pause(); 414 return; 415 } 416 __asm__ volatile("sfence" ::: "memory"); /* the last strips leave the write-combining buffers first */ 417 __asm__ volatile("monitor" ::"a"(&park.gen), "c"(0), "d"(0)); 418 if (__atomic_load_n(&park.gen, __ATOMIC_ACQUIRE) == g) 419 __asm__ volatile("mwait" ::"a"(rest_hint), "c"(0) : "memory"); 420 } 421 static void rest_wake(void) { __atomic_fetch_add(&park.gen, 1, __ATOMIC_RELEASE); } 422 static void rest_boot(void); /* after the LAPIC registers, below */ 423 424 /* The processor's own energy counter (RAPL MSR_PKG_ENERGY_STATUS 0x611, units 425 * in MSR_RAPL_POWER_UNIT 0x606 bits 12:8): read only on Intel client cores from 426 * Skylake on (the iMac's i5-7500 is model 0x9e) and never under a hypervisor, 427 * where the MSR may not exist and reading it would fault. 32 bits that wrap in 428 * about an hour at 65 W, so sampled each second into microjoules. */ 429 static struct { 430 int on; 431 uint32_t esu, last; 432 uint64_t uj, t0, next; 433 } meter; 434 435 static const char *meter_start(void) 436 { 437 static const uint8_t models[] = {0x4e, 0x5e, 0x8e, 0x9e, 0xa5, 0xa6}; 438 uint32_t r[4]; 439 ck_cpuid(1, 0, r); 440 if (r[2] >> 31 & 1) 441 return "none (under a hypervisor)"; 442 uint32_t sig = r[0]; 443 ck_cpuid(0, 0, r); 444 if (r[1] != 0x756e6547u) /* "Genu" */ 445 return "none (not an Intel processor)"; 446 r[0] = sig; 447 uint32_t family = r[0] >> 8 & 0xfu, model = (r[0] >> 4 & 0xfu) | (r[0] >> 12 & 0xf0u); 448 int known = 0; 449 for (unsigned i = 0; i < sizeof models; i++) 450 known |= family == 6 && model == models[i]; 451 if (!known) 452 return "none (not an Intel client core from Skylake on)"; 453 meter.esu = (uint32_t)(ck_rdmsr(0x606) >> 8 & 0x1fu); 454 meter.last = (uint32_t)ck_rdmsr(0x611); 455 meter.t0 = meter.next = ck_rdtsc(); 456 meter.on = 1; 457 return "rapl package"; 458 } 459 static void meter_step(uint64_t now) 460 { 461 if (!meter.on || now < meter.next) 462 return; 463 uint32_t e = (uint32_t)ck_rdmsr(0x611); 464 meter.uj += ((uint64_t)(uint32_t)(e - meter.last) * 1000000u) >> meter.esu; 465 meter.last = e; 466 meter.next = now + tsc_hz; 467 } 468 /* The processor's average since the last line, then the count starts again. */ 469 static void meter_line(const char *when) 470 { 471 if (!meter.on) 472 return; 473 uint64_t now = ck_rdtsc(); 474 meter.next = 0; 475 meter_step(now); 476 uint64_t ms = (now - meter.t0) * 1000u / tsc_hz; 477 if (ms >= 1000) { 478 uint64_t mw = meter.uj / ms; 479 ck_printf("power: processor %llu.%llu W on average over %llu s %s\n", (unsigned long long)(mw / 1000), 480 (unsigned long long)(mw / 100 % 10), (unsigned long long)(ms / 1000), when); 481 } 482 meter.uj = 0; 483 meter.t0 = now; 484 } 485 486 static void draw_stop(void); 487 488 /* A black GOP framebuffer proves nothing about the backlight. Never guess 489 * Intel/AMD registers when the existing AMD path is unsupported or fails. 490 * ACPI S5 is already hardware-documented for this iMac in 491 * evidence/imac_kernel0_2026-10-16/README.md. Deliberately bypass the REPORT 492 * build's no-key reboot policy: this is a requested display-off transition. */ 493 static __attribute__((noreturn)) void panel_poweroff(const char *why) 494 { 495 ck_printf("power: %s; ACPI S5 fallback (power button to start; no any-key wake)\n", why); 496 ck_cli(); 497 draw_stop(); 498 ck_x86_kbd_done(); 499 acpi_poweroff(); 500 ck_puts("power: ACPI S5 failed; display-off not confirmed; halted (no restart); hold the power button to turn off\n"); 501 for (;;) 502 __asm__ volatile("hlt"); 503 } 504 505 static void allen_sleep(int on) 506 { 507 if (allen_asleep == on) 508 return; 509 meter_line(on ? "awake" : "asleep"); 510 if (on) { 511 ck_local_wire_begin(0); 512 __atomic_store_n(&allen_asleep, 1, __ATOMIC_RELEASE); 513 ck_allen_ui_sleep(1, ck_rdtsc()); /* the picture goes to black first */ 514 panel_due = ck_rdtsc() | 1; /* then the panel (panel_step), then the cores rest */ 515 ck_puts("power: preparing display off; unconfirmed panel off uses ACPI S5\n"); 516 return; 517 } 518 panel_due = 0; /* waking during the fade needs no panel restore */ 519 if (panel_dark && ck_x86_panel_on()) 520 panel_poweroff("panel restore failed"); 521 panel_dark = 0; 522 __atomic_store_n(&allen_asleep, 0, __ATOMIC_RELEASE); 523 ck_allen_ui_sleep(0, ck_rdtsc()); /* then the picture comes back */ 524 rest_wake(); /* after the UI has the news: a woken core draws the sky again */ 525 allen_key = ck_rdtsc(); 526 ck_x86_kbd_discard(); 527 ck_puts("power: Allen awake\n"); 528 } 529 530 /* Once the picture is black (or PANEL_WAIT_S has passed), require a confirmed 531 * panel-off result. The old !ready return silently kept the backlight lit, 532 * and the ignored off result did the same on a failed sequence. */ 533 static void panel_step(void) 534 { 535 if (!panel_due || !allen_asleep) 536 return; 537 uint64_t now = ck_rdtsc(), began = panel_due; 538 int black = ck_allen_ui_asleep(); 539 if (!black && now - began < (uint64_t)PANEL_WAIT_S * tsc_hz) 540 return; 541 panel_due = 0; 542 if (!black) 543 ck_printf("screen: the picture did not go black within %u s; proceeding with display off\n", (unsigned)PANEL_WAIT_S); 544 if (!ck_x86_panel_ready()) 545 panel_poweroff("panel off unsupported"); 546 ck_printf("screen: display-off transition %llu ms after the rest began; switching the panel off\n", 547 (unsigned long long)((now - began) / (tsc_hz / 1000))); 548 if (ck_x86_panel_off()) 549 panel_poweroff("panel off not confirmed"); 550 panel_dark = 1; 551 ck_puts("power: Allen asleep (panel registers confirm off; any key or a tap of the power button wakes him)\n"); 552 } 553 554 #define STEP_MAX 16 555 static struct { 556 const char *name; 557 uint64_t tsc; 558 } steps[STEP_MAX]; 559 static unsigned nsteps; 560 561 void ck_x86_step(const char *name) 562 { 563 if (nsteps < STEP_MAX) 564 steps[nsteps].name = name, steps[nsteps++].tsc = ck_rdtsc(); 565 } 566 static void night_stats(const char *when); 567 static ck_allen_facts allen_facts; /* filled at the summary line */ 568 static ck_allen_mind allen_mind; 569 static const ck_courier *courier; /* to a far-off worker (NULL: no wire on this machine) */ 570 static uint32_t job_seq; /* the last job sent down it */ 571 static uint64_t job_t; /* TSC when that job went (0: nothing out) */ 572 static uint64_t job_last; /* TSC of the last word from the far side about it (the silence clock) */ 573 static char job_buf[CK_COURIER_JOB_MAX]; 574 static char job_asked[96]; /* the line the job was about, for Allen's note of the exchange */ 575 /* Code asked of the Spark (svc/allen_code.h): one code job at a time, beside 576 * no other job. The pieces gather in code_rx; the wait is on the TSC in ms. */ 577 static ck_code_rx code_rx; 578 static ck_code_wait code_wait; 579 static uint32_t code_job; /* the code job out (0: none) */ 580 static uint64_t code_t; /* TSC when it went */ 581 static int code_again; /* asked again once already */ 582 static int code_lines_shown; /* lines of the code on the screen (0: none yet) */ 583 static ck_allen_notes allen_notes; /* loaded from disk at the window, or empty */ 584 static struct ck_x86_setup_facts setup_facts; /* what the setup wizard is told at the window */ 585 static uint64_t ram_bytes; /* RAM in the memory map */ 586 587 static void allen_edit(const char *buf, unsigned len) 588 { 589 allen_key = ck_rdtsc(); 590 if (allen_asleep) { /* the key only wakes him */ 591 allen_sleep(0); 592 return; 593 } 594 ck_allen_ui_input(buf, len, ck_rdtsc()); 595 } 596 597 /* The notes map beside the window: the newest live notes (point 0 the newest) 598 * and the links among them; every live note and link is counted. */ 599 static void allen_map(void) 600 { 601 static uint32_t idx[CK_ALLEN_UI_MAP_NODES]; 602 static uint8_t ea[CK_ALLEN_UI_MAP_LINKS], eb[CK_ALLEN_UI_MAP_LINKS]; 603 unsigned n = 0, ne = 0, total = 0, links = 0; 604 int lit = -1; 605 for (uint32_t i = allen_notes.n; i-- > 0;) { 606 if (allen_notes.note[i].gone) 607 continue; 608 total++; 609 for (uint32_t j = i + 1; j < allen_notes.n; j++) 610 links += !allen_notes.note[j].gone && ck_allen_note_links(&allen_notes.note[i], &allen_notes.note[j]) > 0; 611 if (n == CK_ALLEN_UI_MAP_NODES) 612 continue; 613 if (allen_mind.lit == (int)i + 1) 614 lit = (int)n; 615 for (unsigned k = 0; k < n && ne < CK_ALLEN_UI_MAP_LINKS; k++) 616 if (ck_allen_note_links(&allen_notes.note[i], &allen_notes.note[idx[k]]) > 0) { 617 ea[ne] = (uint8_t)k; 618 eb[ne++] = (uint8_t)n; 619 } 620 idx[n++] = i; 621 } 622 ck_allen_ui_map(n, ea, eb, ne, lit, lit >= 0 ? allen_notes.note[idx[lit]].text : 0, total, links); 623 } 624 625 /* Keys while the setup wizard is up go to it whole (never echoed or logged). */ 626 static int wizard_key(int kind, char c) 627 { 628 if (!ck_x86_setup_on()) 629 return 0; 630 allen_key = ck_rdtsc(); 631 if (allen_asleep) { /* the key only wakes him */ 632 allen_sleep(0); 633 return 1; 634 } 635 return ck_x86_setup_key(kind, c); 636 } 637 638 /* Keys while code is on the screen: Up, Down, Page Up, Page Down, Home and End 639 * move it (taken whole), Escape puts it away; anything else goes to the line. */ 640 static int code_key(int kind, char c) 641 { 642 (void)c; 643 if (!ck_allen_ui_code_on()) 644 return 0; 645 if (kind == CK_KEY_ESCAPE) { 646 ck_allen_ui_code(0, 0, 0, ck_rdtsc()); 647 ck_printf("allen-code: code put away\n"); 648 return 1; 649 } 650 int d = kind == CK_KEY_UP ? -1 651 : kind == CK_KEY_DOWN ? 1 652 : kind == CK_KEY_PGUP ? -CK_ALLEN_UI_CODE_PAGE 653 : kind == CK_KEY_PGDN ? CK_ALLEN_UI_CODE_PAGE 654 : kind == CK_KEY_HOME ? -(int)CK_CODE_MAX 655 : kind == CK_KEY_END ? (int)CK_CODE_MAX 656 : 0; 657 if (!d) 658 return 0; 659 allen_key = ck_rdtsc(); 660 unsigned top = 0, rows = 0, page = 0; 661 if (ck_allen_ui_code_scroll(d, &top, &rows, &page) >= 0) 662 ck_printf("allen-code: rows %u to %u of %u shown\n", top + 1, top + page < rows ? top + page : rows, rows); 663 return 1; 664 } 665 666 static int line_key(int kind, char c) { return wizard_key(kind, c) || code_key(kind, c); } 667 668 static uint64_t now_ms(void) { return ck_rdtsc() / (tsc_hz / 1000 ? tsc_hz / 1000 : 1); } 669 670 /* A coding request: Allen says at once that he needs to code it and sends it 671 * to the Spark (courier job "code", or "code-more" for a change to the code 672 * on the screen), then goes on thinking until the code comes (courier_step). 673 * With no Spark he says so plainly. 0: not a coding request. */ 674 static int code_request(const char *text) 675 { 676 char folded[CK_COURIER_LINE_MAX]; 677 ck_allen_fold(text, folded, sizeof folded); 678 int more = ck_allen_ui_code_on() && ck_allen_code_more(folded); 679 if (!more && !ck_allen_wants_code(folded)) 680 return 0; 681 uint64_t t0 = allen_key; 682 const char *say; 683 unsigned n = 0; 684 int sent = 0; 685 if (!courier || !courier->ready()) 686 say = "I'd need to code that on the Spark, and I can't reach it right now. Is it switched on?"; 687 else if (code_job || job_t) 688 say = "Give me a moment, the Spark is still on your last request."; 689 else if (!(n = ck_allen_code_job(&allen_mind, job_seq + 1, text, more, job_buf, sizeof job_buf)) || 690 courier->send(job_buf, n) != 0) 691 say = "I couldn't send that to the Spark. Try it once more?"; 692 else { 693 code_job = ++job_seq; 694 code_t = ck_rdtsc() | 1; 695 code_again = 0; 696 ck_code_begin(&code_rx, code_job); 697 ck_code_wait_begin(&code_wait, now_ms()); 698 sent = 1; 699 say = more ? "Let me take that change to the Spark." : "I need to code that. Let me send it off to the Spark."; 700 } 701 ck_printf("allen: %s\n", say); 702 ck_allen_ui_said(text, say, ck_rdtsc()); 703 if (sent) { 704 ck_allen_ui_working(1); 705 ck_printf("allen-code: asked the Spark (%u chars)\n", (unsigned)strlen(text)); 706 ck_printf("allen-code: acknowledged in %llu ms (job %u, %s)\n", 707 (unsigned long long)((ck_rdtsc() - t0) * 1000 / tsc_hz), (unsigned)code_job, more ? "a change" : "new code"); 708 } else { 709 ck_printf("allen-code: not asked (%s)\n", !courier || !courier->ready() ? "the Spark is not reachable" : "busy or not sent"); 710 } 711 return 1; 712 } 713 714 /* The end of a code job: the code shown, asked again once, or given up out loud. */ 715 static void code_done(const char *sentence) 716 { 717 int st = ck_code_state(&code_rx); 718 uint64_t now = ck_rdtsc(); 719 if ((st == CK_CODE_PART || st == CK_CODE_BAD) && !code_again && courier) { 720 char again[32]; 721 unsigned n = (unsigned)ck_snprintf(again, sizeof again, "AGAIN %u", (unsigned)code_job); 722 ck_printf("allen-code: %s, asked again\n", st == CK_CODE_BAD ? "the checksum did not match" : "a piece went missing"); 723 code_again = 1; 724 ck_code_begin(&code_rx, code_job); 725 ck_code_wait_heard(&code_wait, now_ms()); 726 if (courier->send(again, n) == 0) 727 return; 728 } 729 const char *say = sentence && sentence[0] ? sentence : "Here it is."; 730 if (st == CK_CODE_WHOLE) { 731 ck_allen_ui_code(code_rx.text, code_rx.bytes, code_rx.lang, now); 732 code_lines_shown = (int)ck_code_lines(code_rx.text, code_rx.bytes); 733 ck_printf("allen-code: code shown, %u lines in %llu ms\n", (unsigned)code_lines_shown, 734 (unsigned long long)((now - code_t) * 1000 / tsc_hz)); 735 ck_printf("allen-code: %u bytes, crc32 %08x, %u pieces, language %s\n", (unsigned)code_rx.bytes, 736 (unsigned)code_rx.crc, (unsigned)code_rx.n, code_rx.lang[0] ? code_rx.lang : "none"); 737 /* the first lines on COM1 (the QEMU gate reads them back; never in the lab report) */ 738 unsigned line = 0; 739 for (uint32_t i = 0, s = 0; i <= code_rx.bytes && line < 40; i++) 740 if (i == code_rx.bytes || code_rx.text[i] == '\n') { 741 if (i > s || i < code_rx.bytes) { 742 char row[200]; /* a longer line is echoed cut (the checksum covers the whole) */ 743 uint32_t k = 0; 744 for (; k < i - s && k + 1 < sizeof row; k++) 745 row[k] = code_rx.text[s + k]; 746 row[k] = 0; 747 ck_printf("code|%s\n", row); 748 } 749 s = i + 1; 750 line++; 751 } 752 } else if (st != CK_CODE_NONE) { 753 say = "The code got lost on the way from the Spark. Ask me again?"; 754 ck_printf("allen-code: lost (%u of %u pieces, %u refused)\n", (unsigned)code_rx.got, (unsigned)code_rx.n, 755 (unsigned)code_rx.refused); 756 } else { 757 ck_printf("allen-code: the Spark answered without code\n"); 758 } 759 ck_printf("allen: %s\n", say); 760 ck_allen_ui_said(0, say, now); 761 ck_allen_ui_working(0); 762 code_job = 0; 763 } 764 /* a is b (lower case), whatever a's letter case and the spaces around them */ 765 static int same_words(const char *a, const char *b) 766 { 767 while (*a == ' ') 768 a++; 769 for (; *b; a++, b++) { 770 char x = *a >= 'A' && *a <= 'Z' ? (char)(*a + 32) : *a; 771 if (!*a || x != *b) 772 return 0; 773 } 774 while (*a == ' ') 775 a++; 776 return *a == 0; 777 } 778 779 static void allen_line(const char *text) 780 { 781 allen_key = ck_rdtsc(); 782 if (allen_asleep) { 783 allen_sleep(0); 784 return; 785 } 786 if (allen_on && same_words(text, "set up again") && ck_x86_setup_open(&setup_facts, courier, tsc_hz, 1)) 787 return; /* the setup wizard from its first screen; it says hello itself */ 788 if (allen_on && code_request(text)) 789 return; 790 /* A far-off worker that has said hello answers first (svc/allen_reply.h far). */ 791 allen_mind.far = courier && courier->ready(); 792 const char *reply = ck_allen_answer(&allen_mind, text, ck_rdtsc() / tsc_hz); 793 /* What was taught goes to disk before Allen says it will remember it: a 794 * note first, then the memory copy that counts it; goodbye saves the line 795 * count. A failed write is said out loud. */ 796 int save = allen_mind.changed || reply == ck_allen_goodbye; 797 if (allen_mind.lasting && allen_mind.note_dirty && 798 ck_x86_notes_write(&allen_notes, (uint32_t)allen_mind.note_dirty - 1u)) { 799 allen_mind.lasting = 0; 800 reply = ck_allen_save_failed; 801 } 802 if (allen_mind.lasting && save && ck_x86_memory_save(&allen_mind.mem)) { 803 allen_mind.lasting = 0; 804 if (allen_mind.changed) 805 reply = ck_allen_save_failed; 806 } 807 if (allen_mind.changed) 808 ck_allen_ui_named(ck_allen_self(&allen_mind)); 809 allen_mind.changed = 0; 810 if (allen_mind.sky_changed) { 811 ck_allen_ui_sky_mode(allen_mind.mem.sky_mode, allen_mind.mem.sky_region, 812 allen_mind.mem.sky_lat_udeg, allen_mind.mem.sky_lon_udeg); 813 allen_mind.sky_changed = 0; 814 } 815 if (allen_mind.map_changed || allen_mind.note_dirty) 816 allen_map(); 817 allen_mind.map_changed = 0; 818 allen_mind.note_dirty = 0; 819 /* Nothing here could answer: when a courier is ready, Allen writes the job 820 * himself and keeps thinking until the far side answers (courier_step). */ 821 if (reply == ck_allen_not_yet && courier && courier->ready() && !job_t && !code_job) { 822 unsigned n = ck_allen_job(&allen_mind, job_seq + 1, text, job_buf, sizeof job_buf); 823 if (n) /* his memory rides along: his name, the person's, the facts, the newest notes */ 824 n += ck_allen_job_memory(&allen_mind, 6, job_buf + n, sizeof job_buf - n); 825 if (n && n + 16 < sizeof job_buf) { 826 memcpy(job_buf + n, "\tlocal-tools=v1", 15); n += 15; job_buf[n] = 0; 827 } 828 if (n && courier->send(job_buf, n) == 0) { 829 job_seq++; 830 ck_local_wire_begin(job_seq); 831 job_t = job_last = ck_rdtsc() | 1; 832 ck_snprintf(job_asked, sizeof job_asked, "%s", text); 833 ck_printf("allen: (asking the far side, job %u)\n", (unsigned)job_seq); 834 ck_printf("screen: Allen asked the far side (%u characters in, %u in the job)\n", (unsigned)strlen(text), n); 835 ck_allen_ui_think(text, ck_rdtsc()); 836 return; 837 } 838 } 839 if (reply == ck_allen_not_yet && allen_mind.far) /* the far side is there but could not take it, or is still on the last line */ 840 reply = job_t || code_job ? "Give me a moment, I'm still on your last line." : ck_allen_lost_thread; 841 ck_printf("allen: %s\n", reply); 842 /* the only line about it the lab report may carry: lengths, no words */ 843 ck_printf("screen: Allen answered (%u characters in, %u out)\n", (unsigned)strlen(text), (unsigned)strlen(reply)); 844 ck_allen_ui_said(text, reply, ck_rdtsc()); 845 if (reply == ck_allen_goodbye && !allen_bye) 846 allen_bye = ck_rdtsc() | 1; 847 if (reply == ck_allen_goodbye) 848 night_stats("by goodbye"); 849 } 850 851 /* The startup screen (ui/allen_ui.c): the night sky from the moment the clock 852 * is measured, Allen formed in it by the time the keyboard is ready. Until 853 * the secondary cores are up the boot core draws a frame between console 854 * writes (night_tick); then the first secondary core draws the frames 855 * (draw_loop) and the next two draw strips of them (help_loop). draw_lock 856 * keeps to one frame at a time whoever draws it. */ 857 static uint32_t night_ms, night_mib; /* what is said about it once the console is up */ 858 static uint64_t night_t0; /* when the night began (TSC); the chirp keeps time with it */ 859 static uint64_t night_last, night_cost; /* the boot core's last frame and what it took */ 860 static volatile uint32_t draw_run, draw_on, draw_helpers; /* drawing allowed; a core draws frames; cores helping */ 861 /* core/spinlock.h without the interrupt mask: no interrupt handler draws, and the drawing cores keep interrupts on 862 * to acknowledge TLB-shootdown IPIs; a core spinning here with interrupts masked could block a shootdown. */ 863 static struct ck_spinlock draw_lock = CK_SPINLOCK_INIT; 864 865 static uint64_t night_clock(void) { return ck_rdtsc(); } 866 867 /* After each console write, while no secondary core draws: a frame when one 868 * is due, with at least twice a frame's drawing time between frames, so 869 * startup is not slowed by more than a third. */ 870 static void night_tick(void) 871 { 872 ck_x86_hda_step(); 873 uint64_t now = ck_rdtsc(); 874 if (__atomic_load_n(&draw_on, __ATOMIC_ACQUIRE) || now - night_last < night_cost * 2 || 875 !ck_spin_trylock_nomask(&draw_lock)) 876 return; 877 if (ck_allen_ui_tick(now)) { 878 night_last = ck_rdtsc(); 879 night_cost = night_last - now; 880 } 881 ck_spin_unlock_nomask(&draw_lock); 882 } 883 884 /* The secondary cores' work while the night is up; each returns to its halt 885 * once draw_stop clears draw_run. While Allen sleeps they rest (rest_wait): 886 * the frame core once its frame has put the dark screen up, the helpers at 887 * once (the frame core draws any strip they leave). park.gen is read before 888 * the state it guards, so a wake between the two is never missed. */ 889 /* Every pass of a drawing core ends in a PAUSE, a frame drawn or not. When the 890 * water came (`f913a63`) a frame under QEMU TCG took longer than FRAME_MS, so the 891 * frame core drew frame after frame and never reached its PAUSE: a virtual CPU 892 * that never leaves its translated code never passes an RCU quiescent point, 893 * and QEMU's device_add waits for one (drain_call_rcu). The keyboard replug test 894 * then hung inside device_add with the monitor blocked, and the keys it types 895 * afterwards never arrived (L411, 2026-10-22, gdb stacks: main thread in 896 * qmp_device_add > drain_call_rcu, vCPU 1 in code_gen_buffer). On the iMac a 897 * PAUSE per frame or strip costs nothing. */ 898 static void draw_loop(void) 899 { 900 __atomic_store_n(&draw_on, 1, __ATOMIC_RELEASE); 901 while (__atomic_load_n(&draw_run, __ATOMIC_ACQUIRE)) { 902 uint32_t g = __atomic_load_n(&park.gen, __ATOMIC_ACQUIRE); 903 ck_spin_lock_nomask(&draw_lock); 904 (void)ck_allen_ui_tick(ck_rdtsc()); /* drawn or not, the pass ends in a PAUSE */ 905 int dark = ck_allen_ui_asleep(); 906 ck_spin_unlock_nomask(&draw_lock); 907 if (dark) 908 rest_wait(g); 909 else 910 ck_pause(); /* also after a frame: see above */ 911 } 912 __atomic_store_n(&draw_on, 0, __ATOMIC_RELEASE); 913 } 914 static void help_loop(void) 915 { 916 __atomic_fetch_add(&draw_helpers, 1, __ATOMIC_ACQ_REL); 917 while (__atomic_load_n(&draw_run, __ATOMIC_ACQUIRE)) { 918 uint32_t g = __atomic_load_n(&park.gen, __ATOMIC_ACQUIRE); 919 if (ck_allen_ui_help()) { 920 ck_pause(); /* one PAUSE per strip: see draw_loop */ 921 continue; 922 } 923 if (ck_allen_ui_asleep()) /* keep helping until the final black frame is presented */ 924 rest_wait(g); 925 else 926 ck_pause(); 927 } 928 __atomic_fetch_sub(&draw_helpers, 1, __ATOMIC_ACQ_REL); 929 } 930 931 /* Before text goes back on the screen: the drawing cores finish the frame in 932 * hand and stop. Waits at most 200 ms (a panic never hangs here); then the 933 * frame lock is held for good, so nothing draws over the text. */ 934 static void draw_stop(void) 935 { 936 __atomic_store_n(&draw_run, 0, __ATOMIC_RELEASE); 937 rest_wake(); /* resting cores see draw_run cleared */ 938 if (!tsc_hz) 939 return; 940 uint64_t t0 = ck_rdtsc(); 941 while ((draw_on || draw_helpers) && ck_rdtsc() - t0 < tsc_hz / 5) 942 ck_pause(); 943 while (!ck_spin_trylock_nomask(&draw_lock) && ck_rdtsc() - t0 < tsc_hz / 5) 944 ck_pause(); 945 } 946 947 static void night_stats(const char *when) 948 { 949 uint32_t n, slowest, average; 950 ck_allen_ui_stats(&n, &slowest, &average); 951 ck_printf("screen: night: %u frames %s, average %u.%u ms, slowest %u.%u ms (drawn by %s)\n", n, when, 952 average / 1000, average / 100 % 10, slowest / 1000, slowest / 100 % 10, 953 draw_on ? "a secondary core" : "the boot core"); 954 ck_allen_ui_dusk_stats(&n, &slowest, &average); 955 if (n) 956 ck_printf("screen: dusk: %u frames, average %u.%u ms, slowest %u.%u ms\n", n, average / 1000, 957 average / 100 % 10, slowest / 1000, slowest / 100 % 10); 958 } 959 960 /* Time since the power button for each step. The TSC counts from power-on 961 * (and from every reset), so its value at a step is the time since then: 962 * firmware until the loader (or this kernel) starts, the loader, this kernel 963 * until Allen's window takes the screen and the keyboard. */ 964 static void boot_times(void) 965 { 966 const struct nb_pass *np = ck_x86_netldr_pass(0); 967 uint64_t per_ms = tsc_hz / 1000u, entry = hand->uefi_entry_ticks; 968 if (!per_ms) 969 return; 970 if (np) 971 ck_printf("boot_time: since power on: firmware until the loader %llu ms, loader %llu ms, kernel %llu ms; " 972 "Allen's window at %llu ms\n", (unsigned long long)(np->loader_tsc / per_ms), 973 (unsigned long long)((entry - np->loader_tsc) / per_ms), 974 (unsigned long long)((allen_woke - entry) / per_ms), (unsigned long long)(allen_woke / per_ms)); 975 else 976 ck_printf("boot_time: since power on: firmware until this kernel %llu ms (no loader), kernel %llu ms; " 977 "Allen's window at %llu ms\n", (unsigned long long)(entry / per_ms), 978 (unsigned long long)((allen_woke - entry) / per_ms), (unsigned long long)(allen_woke / per_ms)); 979 /* each step of this kernel, and when the night reached the screen */ 980 static char line[240]; /* the report keeps lines up to 240 characters */ 981 uint64_t prev = entry; 982 int n = ck_snprintf(line, sizeof line, "boot_time: steps in ms:"); 983 for (unsigned k = 0; k < nsteps && n > 0 && (size_t)n < sizeof line; k++) { 984 n += ck_snprintf(line + n, sizeof line - (size_t)n, " %s %llu", steps[k].name, 985 (unsigned long long)((steps[k].tsc - prev) / per_ms)); 986 prev = steps[k].tsc; 987 } 988 ck_printf("%s window %llu; the night on screen at %llu ms\n", line, (unsigned long long)((allen_woke - prev) / per_ms), 989 night_t0 ? (unsigned long long)(night_t0 / per_ms + night_ms) : 0ull); 990 } 991 992 static int64_t rtc_unix(void); /* forward declaration; defined below */ 993 static void allen_window(void) 994 { 995 static char footer[64]; 996 volatile uint32_t *px; 997 uint32_t w, h, pitch, format; 998 uint64_t pa; 999 ck_x86_step("keyboard"); 1000 ck_allen_mind_init(&allen_mind, &allen_facts); 1001 allen_mind.notes = &allen_notes; 1002 if (ck_x86_memory_open(&allen_mind.mem, &allen_notes, tsc_hz)) { 1003 allen_mind.lasting = 1; 1004 allen_mind.mem.starts++; 1005 if (ck_x86_memory_save(&allen_mind.mem)) 1006 allen_mind.lasting = 0; 1007 } else { 1008 allen_notes.n = 0; /* nothing half-loaded is kept */ 1009 allen_mind.mem.nnotes = 0; 1010 } 1011 ck_x86_step("memory"); 1012 courier = 0; 1013 #if CK_X86_REPORT 1014 courier = ck_x86_courier_udp(tsc_hz); /* lab image: Ethernet to the far side when the chip is up (it says so itself) */ 1015 #endif 1016 if (!courier) { 1017 courier = ck_x86_courier_init(); 1018 ck_printf(courier ? "courier: a second serial port answers; Allen can ask a far-off worker once it says hello\n" 1019 : "courier: no second serial port; Allen answers from this computer alone\n"); 1020 } 1021 ck_allen_ui_named(ck_allen_self(&allen_mind)); /* the bar says who to speak to */ 1022 ck_x86_kbd_sink(0, allen_line); 1023 #ifdef CK_X86_SWAP_TEST_DISK 1024 /* QEMU swap test only (never in a lab image that reaches the iMac): teach Allen 1025 * one fact through the real line path so kernel A writes Allen's memory to disk 1026 * before the swap, and the swapped-in kernel must load it back. */ 1027 allen_line("my name is Ada"); 1028 #endif 1029 if (ck_x86_console_fb_get(&px, &w, &h, &pitch, &format)) { 1030 ck_puts("screen: text only (no framebuffer for Allen's window)\n"); 1031 return; 1032 } 1033 allen_facts.screen_w = w; 1034 allen_facts.screen_h = h; 1035 allen_mind.facts = allen_facts; 1036 if (!ck_allen_ui_started()) { /* the night could not start at boot: Allen's home starts here */ 1037 size_t need = ck_allen_ui_mem_bytes(w, h); 1038 uint64_t pages = (need + CK_PAGE - 1) / CK_PAGE; 1039 if (ck_frames_alloc(&frames, pages, CK_PAGE, &pa)) { 1040 ck_printf("screen: text only (no %llu MiB for Allen's window)\n", (unsigned long long)(need >> 20)); 1041 return; 1042 } 1043 if (ck_allen_ui_start(px, w, h, pitch, format, (void *)(uintptr_t)pa, pages * CK_PAGE, tsc_hz, ck_rdtsc(), 1044 night_clock)) { 1045 ck_puts("screen: text only (Allen's window refused the screen)\n"); 1046 ck_frames_free(&frames, pa, pages); 1047 return; 1048 } 1049 night_mib = (uint32_t)(need >> 20); 1050 } 1051 ck_snprintf(footer, sizeof footer, ck_x86_panel_ready() ? 1052 "Goodbye: screen off; power off if panel control fails" : 1053 "Goodbye powers off; power button starts this computer"); 1054 ck_printf("screen: Allen's window (%ux%u, %u MiB drawing memory)\n", w, h, night_mib); 1055 ck_x86_console_fb_off(); 1056 ck_allen_ui_refresh(); /* whatever else was on the screen goes */ 1057 ck_allen_ui_wake(footer, ck_rdtsc()); 1058 /* Read the real-time clock (CMOS ports 0x70/0x71) for sidereal sky calculations */ 1059 { 1060 int64_t rtc_s = rtc_unix(); 1061 if (rtc_s > 0) 1062 ck_allen_ui_set_unix_time(rtc_s, ck_rdtsc()); 1063 } 1064 /* Apply sky mode saved in Allen's memory */ 1065 if (allen_mind.mem.sky_mode) 1066 ck_allen_ui_sky_mode(allen_mind.mem.sky_mode, allen_mind.mem.sky_region, 1067 allen_mind.mem.sky_lat_udeg, allen_mind.mem.sky_lon_udeg); 1068 ck_x86_kbd_sink(allen_edit, allen_line); 1069 allen_on = 1; 1070 allen_woke = allen_key = ck_rdtsc(); 1071 power_button_watch(); 1072 const char *meter_how = meter_start(); 1073 if (CK_X86_IDLE_S) 1074 ck_printf("power: this computer rests after %u s without a key\n", (unsigned)CK_X86_IDLE_S); 1075 else 1076 ck_puts("power: this computer does not rest by itself\n"); 1077 if (rest_mwait) 1078 ck_printf("power: asleep, the drawing cores rest in mwait (hint 0x%x) and the boot core in mwait between " 1079 "keyboard polls every %u ms; meter: %s\n", rest_hint, REST_MS, meter_how); 1080 else 1081 ck_printf("power: asleep, the drawing cores spin (no MONITOR/MWAIT) and the boot core halts between " 1082 "keyboard polls every %u ms; meter: %s\n", REST_MS, meter_how); 1083 boot_times(); 1084 night_stats("before Allen woke"); 1085 allen_map(); /* the notes loaded from disk, before the first word */ 1086 setup_facts = (struct ck_x86_setup_facts){hand->rsdp, ram_bytes, allen_facts.cores, w, h, allen_mind.mem.starts}; 1087 ck_x86_kbd_keys(line_key); 1088 if (ck_x86_setup_open(&setup_facts, courier, tsc_hz, 0)) 1089 return; /* the setup wizard says hello in its own words */ 1090 const char *hello = ck_allen_welcome(&allen_mind); 1091 if (hello) { 1092 ck_printf("allen: %s\n", hello); 1093 ck_allen_ui_said(0, hello, ck_rdtsc()); 1094 } 1095 } 1096 1097 static int same_text(const char *a, const char *b) 1098 { 1099 while (*a && *a == *b) 1100 a++, b++; 1101 return *a == *b; 1102 } 1103 1104 /* Allen's note of an exchange he had through the far side: what was asked, 1105 * what he said, one note on disk (svc/allen_reply.h ck_allen_note_exchange), 1106 * so his memory grows with every answer. The cost is printed in ms. */ 1107 static void allen_note_exchange(const char *said) 1108 { 1109 uint64_t t0 = ck_rdtsc(); 1110 if (ck_allen_note_exchange(&allen_mind, job_asked, said)) 1111 return; 1112 int failed = 0; 1113 if (allen_mind.lasting && allen_mind.note_dirty && 1114 ck_x86_notes_write(&allen_notes, (uint32_t)allen_mind.note_dirty - 1u)) 1115 failed = 1; 1116 if (!failed && allen_mind.lasting && ck_x86_memory_save(&allen_mind.mem)) 1117 failed = 1; 1118 if (failed) 1119 allen_mind.lasting = 0; 1120 allen_mind.changed = 0; 1121 allen_mind.note_dirty = 0; 1122 allen_map(); 1123 allen_mind.map_changed = 0; 1124 ck_printf("allen_memory: note %u (the exchange) %s in %llu ms\n", (unsigned)allen_notes.n, 1125 !allen_mind.lasting ? "kept until power off" : "saved", (unsigned long long)((ck_rdtsc() - t0) * 1000 / tsc_hz)); 1126 } 1127 1128 /* Answers from the far side, taken in the hold loop: the parts of the one 1129 * Allen is waiting for are joined and shown as they come (the ink settles 1130 * into words); anything else is dropped. "WAIT" says the far side is held up 1131 * and starts the silence clock over; 30 s of silence gives the job up out 1132 * loud. The console gets Allen's words (COM1); the lab report carries lengths 1133 * and times only. */ 1134 static void courier_step(void) 1135 { 1136 static int said_ready; 1137 static char text[160]; /* one part, folded */ 1138 static char said[160]; /* the parts so far: what the window shows at once (ui TEXT_MAX) */ 1139 static unsigned said_n, parts; 1140 char line[CK_COURIER_LINE_MAX]; 1141 uint32_t seq; 1142 unsigned part, total; 1143 if (!courier) 1144 return; 1145 if (!said_ready && courier->ready()) { 1146 said_ready = 1; 1147 ck_printf("courier: ready, the far side said hello\n"); 1148 } 1149 ck_local_snapshot(allen_facts.cores, ck_frames_free_bytes(&frames), 1150 hand->fb_width, hand->fb_height, 1151 ck_x86_tg3_ready() ? (ck_x86_tg3_link() ? 1 : 2) : 0); 1152 ck_local_wire_step(courier); 1153 while (courier->take(line, sizeof line)) { 1154 if (ck_local_wire_line(line)) continue; 1155 if (ck_x86_setup_line(line)) 1156 continue; /* the setup wizard's key test answered */ 1157 if (code_job) { 1158 int k = ck_code_take(&code_rx, line); 1159 if (k > 0) 1160 ck_code_wait_heard(&code_wait, now_ms()); 1161 if (k) 1162 continue; 1163 if (ck_allen_say_line(line, &seq, &part, &total, text, sizeof text) && seq == code_job) { 1164 ck_code_wait_heard(&code_wait, now_ms()); 1165 if (part && total && part >= total) 1166 code_done(text); 1167 continue; 1168 } 1169 } 1170 if (!ck_allen_say_line(line, &seq, &part, &total, text, sizeof text) || !job_t || seq != job_seq) 1171 continue; 1172 job_last = ck_rdtsc() | 1; 1173 if (part == 0) { /* WAIT: the far side is held up (a busy model); the silence clock starts over */ 1174 static uint32_t waited_job; 1175 if (waited_job != seq) { 1176 waited_job = seq; 1177 ck_printf("screen: the far side is busy, Allen waits for job %u\n", (unsigned)seq); 1178 } 1179 continue; 1180 } 1181 if (part == 1) { 1182 said_n = 0; 1183 parts = 0; 1184 ck_printf("screen: the far side began job %u after %llu ms\n", (unsigned)seq, 1185 (unsigned long long)((job_last - job_t) * 1000 / tsc_hz)); 1186 } 1187 parts++; 1188 if (text[0]) { /* the parts join with a space; what the window cannot hold is left off */ 1189 if (said_n && said_n + 1 < sizeof said) 1190 said[said_n++] = ' '; 1191 for (unsigned i = 0; text[i] && said_n + 1 < sizeof said; i++) 1192 said[said_n++] = text[i]; 1193 said[said_n] = 0; 1194 if (part >= 2) 1195 ck_allen_ui_said_more(said, ck_rdtsc()); 1196 else 1197 ck_allen_ui_said(0, said, ck_rdtsc()); 1198 } 1199 if (total && part >= total) { /* the last part: the answer is whole */ 1200 if (!said_n) { 1201 ck_snprintf(said, sizeof said, "%s", ck_allen_lost_thread); 1202 ck_allen_ui_said(0, said, ck_rdtsc()); 1203 } 1204 ck_printf("allen: %s\n", said); 1205 ck_printf("screen: the far side answered job %u (%u characters out, %u parts, %llu ms)\n", (unsigned)seq, 1206 (unsigned)strlen(said), parts, (unsigned long long)((ck_rdtsc() - job_t) * 1000 / tsc_hz)); 1207 job_t = 0; 1208 ck_local_wire_begin(0); 1209 if (!same_text(said, ck_allen_lost_thread)) /* no note of an exchange that got no answer */ 1210 allen_note_exchange(said); 1211 } 1212 } 1213 if (code_job) { 1214 int w = ck_code_wait_tick(&code_wait, now_ms()); 1215 if (w == CK_CODE_WAIT_SLOW) { 1216 const char *say = "The Spark is still writing it. Longer code takes a little while."; 1217 ck_printf("allen: %s\n", say); 1218 ck_printf("allen-code: the Spark is slow (%u s so far)\n", CK_CODE_SLOW_MS / 1000u); 1219 ck_allen_ui_said(0, say, ck_rdtsc()); 1220 } else if (w == CK_CODE_WAIT_GONE) { 1221 const char *say = "The Spark stopped answering, so I couldn't get the code. Try again in a minute."; 1222 ck_printf("allen: %s\n", say); 1223 ck_printf("allen-code: the Spark stopped answering job %u (%u s of silence)\n", (unsigned)code_job, 1224 CK_CODE_GONE_MS / 1000u); 1225 ck_allen_ui_said(0, say, ck_rdtsc()); 1226 ck_allen_ui_working(0); 1227 code_job = 0; 1228 } 1229 } 1230 if (job_t && ck_rdtsc() - job_last > 30 * tsc_hz) { 1231 job_t = 0; 1232 ck_local_wire_begin(0); 1233 ck_printf("allen: %s\n", ck_allen_lost_thread); 1234 ck_printf("screen: the far side did not answer job %u\n", (unsigned)job_seq); 1235 ck_allen_ui_said(0, ck_allen_lost_thread, ck_rdtsc()); 1236 } 1237 } 1238 1239 /* One step of the hold loop. The devices (keyboard controller, the courier's 1240 * serial port, the power button's PM1 port, the sound controller) are polled 1241 * at most once every POLL_US by the TSC; between polls the loop only spins 1242 * on the clock. Polling them on every pass hit them about a million times a 1243 * second, which under QEMU starved the emulator's main loop of its big lock 1244 * after a keyboard replug (handoff 2026-10-18: the replugged keyboard's keys 1245 * never arrived). 0.5 ms keeps a key under a millisecond late and the 1246 * courier's 16-byte FIFO safe (1.4 ms to fill at 115200 baud). The picture's 1247 * frame (when this core draws it) and the sleep bookkeeping run every pass. */ 1248 #define POLL_US 500u 1249 static uint64_t poll_next; /* TSC of the next device poll */ 1250 1251 void ck_x86_hold_step(uint64_t *end) 1252 { 1253 uint64_t now = ck_rdtsc(); 1254 int poll = (int64_t)(now - poll_next) >= 0; 1255 if (poll) { 1256 poll_next = now + tsc_hz / `1000000` * POLL_US; 1257 ck_x86_hda_step(); 1258 ck_x86_kbd_hold_poll(end); 1259 courier_step(); /* before the window too: the wire's FIFO is 16 bytes, the far side's hello 14 */ 1260 } 1261 /* The lab receivers (swap, bench) run whether or not Allen's window is up: a lab 1262 * iMac with no keyboard must still take a swap or a bench command. */ 1263 ck_x86_swap_step(hand, tramp_pa); 1264 ck_x86_bench_step(tsc_hz); 1265 if (!allen_asleep) 1266 ck_local_step(); 1267 if (!allen_on) 1268 return; 1269 if (!allen_asleep) { 1270 const char *sample = ck_local_model_demo_step(); 1271 if (sample) ck_allen_ui_said(0, sample, ck_rdtsc()); 1272 } 1273 ck_x86_setup_step(); 1274 if (!__atomic_load_n(&draw_on, __ATOMIC_ACQUIRE) && ck_spin_trylock_nomask(&draw_lock)) { 1275 ck_allen_ui_tick(ck_rdtsc()); /* no secondary core draws: this one does */ 1276 ck_spin_unlock_nomask(&draw_lock); 1277 } 1278 static int told; 1279 if (!told && ck_rdtsc() - allen_woke > 20 * tsc_hz) { 1280 told = 1; 1281 night_stats("by 20 s after Allen woke"); 1282 } 1283 /* After goodbye, allow the existing answer delay, then fade to black. 1284 * Idle and a power-button tap use the same confirmed-off/S5 policy. */ 1285 if (allen_bye && ck_rdtsc() - allen_bye > 4 * tsc_hz) { 1286 allen_bye = 0; 1287 allen_sleep(1); 1288 } 1289 if (CK_X86_IDLE_S && !allen_asleep && ck_rdtsc() - allen_key > (uint64_t)CK_X86_IDLE_S * tsc_hz) { 1290 ck_printf("power: no key for %u s; the computer rests\n", (unsigned)CK_X86_IDLE_S); 1291 allen_sleep(1); 1292 } 1293 if (poll && power_button_tapped()) 1294 allen_sleep(!allen_asleep); 1295 panel_step(); 1296 meter_step(ck_rdtsc()); 1297 *end = ~0ull; 1298 if (allen_asleep) 1299 rest_boot(); 1300 } 1301 1302 static __attribute__((noreturn)) void finish(void) 1303 { 1304 ck_cli(); 1305 if (!tsc_hz) { /* no clock yet: keep the screen readable, never power off unseen */ 1306 #if CK_X86_REPORT 1307 ck_puts("power: no clock measured; lab image restarts\n"); 1308 acpi_reset(); 1309 #endif 1310 ck_puts("power: halted before the clock was measured; hold the power button to turn the machine off\n"); 1311 for (;;) 1312 __asm__ volatile("hlt"); 1313 } 1314 if (CK_X86_HOLD_S && ck_x86_kbd_ready()) { 1315 allen_window(); 1316 if (allen_on) 1317 ck_puts("keyboard: type a line and press Enter; goodbye switches the display off; any-key wake only after confirmed panel off, otherwise ACPI S5 (power button to start)\n"); 1318 else 1319 ck_printf("keyboard: type a line and press Enter; the screen stays on until %u s after the last key\n", 1320 ck_x86_kbd_idle_s()); 1321 } 1322 if (!allen_on) { /* no Allen's window: the startup text, not the night */ 1323 draw_stop(); 1324 ck_x86_console_fb_show(); 1325 } 1326 if (CK_X86_HOLD_S) { 1327 /* With Allen's window up the hold does not expire. Rest either 1328 * confirms panel off and permits wake, or powers off through S5. */ 1329 #if CK_X86_REPORT 1330 /* Lab build only (make imac-kernel CK_X86_REPORT=1): sends the 1331 * allowlisted, unauthenticated report if the network is up. */ 1332 if (allen_on) 1333 ck_puts("power: Allen's window stays on; goodbye, idle or a power-button tap switches the display off; confirmed panel off permits any-key wake, otherwise ACPI S5\n"); 1334 else 1335 ck_printf("power: holding the screen %u s, then restart\n", (unsigned)CK_X86_HOLD_S); 1336 ck_x86_report_hold(tsc_hz, CK_X86_HOLD_S); 1337 ck_x86_kbd_done(); 1338 #else 1339 /* Default and resident builds: no report code is linked; nothing is sent. */ 1340 if (allen_on) 1341 ck_puts("power: Allen's window stays on; goodbye, idle or a power-button tap switches the display off; confirmed panel off permits any-key wake, otherwise ACPI S5\n"); 1342 else 1343 ck_printf("power: holding the screen %u s, then ACPI S5\n", (unsigned)CK_X86_HOLD_S); 1344 uint64_t end = ck_rdtsc() + (uint64_t)CK_X86_HOLD_S * tsc_hz; /* typing moves it out */ 1345 while (ck_rdtsc() < end) { 1346 ck_x86_hold_step(&end); 1347 ck_pause(); 1348 } 1349 ck_x86_kbd_done(); 1350 #endif 1351 } 1352 if (allen_on) { /* not reached while the hold holds; if it ever ends, halt: never a restart after goodbye */ 1353 ck_puts("power: Allen's window ended; halted (no restart); hold the power button 4 s to turn the computer off\n"); 1354 for (;;) 1355 __asm__ volatile("hlt"); 1356 } 1357 #if CK_X86_REPORT 1358 acpi_reset(); 1359 #endif 1360 acpi_poweroff(); 1361 ck_puts("power: halted; hold the power button to turn the machine off\n"); 1362 for (;;) 1363 __asm__ volatile("hlt"); 1364 } 1365 1366 void ck_panic(const char *fmt, ...) 1367 { 1368 ck_cli(); 1369 draw_stop(); 1370 ck_x86_console_fb_show(); /* a panic is always readable */ 1371 va_list ap; 1372 va_start(ap, fmt); 1373 ck_puts("panic: "); 1374 ck_vprintf(fmt, ap); 1375 va_end(ap); 1376 ck_puts("\n"); 1377 finish(); 1378 } 1379 1380 /* ---- traps ---- */ 1381 static struct { 1382 volatile int armed, hit; 1383 volatile uint64_t resume, cr2, err; 1384 } probe; 1385 static volatile uint64_t ticks, tick_tsc[32]; 1386 static volatile uint64_t stray_irqs; 1387 /* TLB shootdown (#485, tlb_flush_page): the page every secondary core is to 1388 * flush and how many have done so. */ 1389 static volatile uint64_t tlb_va; 1390 static volatile uint32_t tlb_acks; 1391 static void tlb_probe_run(void); 1392 static volatile uint32_t *xapic; 1393 1394 static const char *const exc_name[32] = { 1395 "#DE", "#DB", "NMI", "#BP", "#OF", "#BR", "#UD", "#NM", "#DF", "?", "#TS", "#NP", "#SS", "#GP", "#PF", "?", 1396 "#MF", "#AC", "#MC", "#XM", "#VE", "#CP", "?", "?", "?", "?", "?", "?", "#HV", "#VC", "#SX", "?"}; 1397 1398 /* The local APIC in xAPIC mode (MMIO, 4 KiB at IA32_APIC_BASE): the mode 1399 * the iMac's firmware leaves it in and the one QEMU TCG emulates. x2APIC 1400 * (MSR access) waits for a test that can run it. */ 1401 static void apic_wr(unsigned reg, uint32_t v) 1402 { 1403 xapic[reg / 4] = v; 1404 } 1405 static uint32_t apic_rd(unsigned reg) 1406 { 1407 return xapic[reg / 4]; 1408 } 1409 #define APIC_ID 0x20 1410 #define APIC_VER 0x30 1411 #define APIC_TPR 0x80 1412 #define APIC_EOI 0xb0 1413 #define APIC_SVR 0xf0 1414 #define APIC_LVT_TIMER 0x320 1415 #define APIC_TIMER_INIT 0x380 1416 #define APIC_TIMER_CUR 0x390 1417 #define APIC_TIMER_DIV 0x3e0 1418 1419 /* The boot core between keyboard polls while Allen sleeps: a one-shot LAPIC 1420 * timer REST_MS out, then STI;MWAIT (or STI;HLT) until its interrupt, which 1421 * STI's one-instruction shadow cannot let slip in before the wait begins. The 1422 * timer was proven at boot (apic_start: 20 ticks or a panic), every other 1423 * interrupt line is masked, and a stray vector is only counted. */ 1424 static void rest_boot(void) 1425 { 1426 if (!lapic_per_ms) 1427 return; 1428 apic_wr(APIC_LVT_TIMER, VEC_TIMER); /* one shot, unmasked; divide 16 as measured */ 1429 apic_wr(APIC_TIMER_INIT, lapic_per_ms * REST_MS); 1430 if (rest_mwait) { 1431 __asm__ volatile("monitor" ::"a"(&park.gen), "c"(0), "d"(0)); 1432 __asm__ volatile("sti; mwait; cli" ::"a"(rest_hint), "c"(0) : "memory"); 1433 } else 1434 __asm__ volatile("sti; hlt; cli" ::: "memory"); 1435 apic_wr(APIC_TIMER_INIT, 0); 1436 apic_wr(APIC_LVT_TIMER, 1u << 16 | VEC_TIMER); 1437 } 1438 1439 void ck_local_machine_stack(uint64_t top) { tss.rsp[0] = top; } 1440 int ck_local_machine_timer(int enable) 1441 { 1442 if (!xapic || !lapic_per_ms) 1443 return -1; 1444 apic_wr(APIC_TIMER_INIT, 0); 1445 apic_wr(APIC_LVT_TIMER, (enable ? 0 : 1u << 16) | VEC_TIMER); 1446 if (enable) 1447 apic_wr(APIC_TIMER_INIT, lapic_per_ms); 1448 return 0; 1449 } 1450 void ck_local_machine_eoi(uint64_t v) 1451 { 1452 if (xapic && v >= 32 && v != 0x80 && v != VEC_SPURIOUS) 1453 apic_wr(APIC_EOI, 0); 1454 } 1455 1456 void ck_x86_trap(struct ck_x86_frame *f) 1457 { 1458 if (f->vector == 14 && probe.armed) { 1459 probe.armed = 0; 1460 probe.hit = 1; 1461 probe.cr2 = ck_rd_cr2(); 1462 probe.err = f->error; 1463 f->rip = probe.resume; 1464 return; 1465 } 1466 if (f->vector == VEC_TLB) { 1467 __asm__ volatile("invlpg (%0)" ::"r"(tlb_va) : "memory"); 1468 apic_wr(APIC_EOI, 0); 1469 __atomic_fetch_add(&tlb_acks, 1, __ATOMIC_RELEASE); 1470 return; 1471 } 1472 if (f->vector == VEC_TLB_PROBE) { 1473 apic_wr(APIC_EOI, 0); /* first, so VEC_TLB can arrive while the probe waits */ 1474 tlb_probe_run(); 1475 return; 1476 } 1477 if (f->vector == VEC_TIMER) { 1478 uint64_t n = ticks; 1479 if (n < 32) 1480 tick_tsc[n] = ck_rdtsc(); 1481 ticks = n + 1; 1482 apic_wr(APIC_EOI, 0); 1483 return; 1484 } 1485 if (f->vector == VEC_SPURIOUS) 1486 return; 1487 if (f->vector >= 32) { 1488 stray_irqs++; 1489 if (xapic) 1490 apic_wr(APIC_EOI, 0); 1491 return; 1492 } 1493 ck_panic("exception: vector %llu %s error=0x%llx rip=0x%llx rsp=0x%llx cr2=0x%llx rflags=0x%llx", 1494 (unsigned long long)f->vector, exc_name[f->vector], (unsigned long long)f->error, 1495 (unsigned long long)f->rip, (unsigned long long)f->rsp, (unsigned long long)ck_rd_cr2(), 1496 (unsigned long long)f->rflags); 1497 } 1498 1499 /* ---- memory ---- */ 1500 struct mm { 1501 uint64_t root, top, pages_wb, pages_wc, pages_uc, pt_frames, fb_lo, fb_hi; 1502 int fb_ok; 1503 }; 1504 static struct mm mm; 1505 static uint64_t *pds[MAP_TOP_MAX >> 30]; 1506 1507 static uint64_t *table_new(void) 1508 { 1509 uint64_t pa; 1510 if (ck_frames_alloc(&frames, 1, CK_PAGE, &pa)) 1511 ck_panic("paging: out of frames for page tables"); 1512 mm.pt_frames++; 1513 memset((void *)(uintptr_t)pa, 0, CK_PAGE); 1514 return (uint64_t *)(uintptr_t)pa; 1515 } 1516 1517 /* EFI types that are RAM (write-back): everything but reserved (0), unusable 1518 * (8), MMIO (11, 12) and persistent memory left to later cuts. */ 1519 static int efi_ram(uint32_t type) 1520 { 1521 return type <= 10 && type != 0 && type != 8; 1522 } 1523 1524 static int in_range(uint64_t p, const char *lo, const char *hi) 1525 { 1526 return p >= (uint64_t)(uintptr_t)lo && p < (uint64_t)(uintptr_t)hi; 1527 } 1528 1529 /* One 4 KiB page of a split 2 MiB page (cache bits from the 2 MiB entry): 1530 * physical page 0 and the stack guard unmapped (a NULL dereference faults, 1531 * #487), code RX, the PE header and read-only data R+NX, everything else 1532 * RW+NX (the trampoline page included until smp_start). */ 1533 static uint64_t leaf_4k(uint64_t p, uint64_t cache) 1534 { 1535 if (p == 0 || p == (uint64_t)(uintptr_t)kstack) 1536 return 0; 1537 if (in_range(p, __text_start, __text_end)) 1538 return p | PTE_P | TEXT_W | cache; 1539 if (in_range(p, __image_base, __text_start) || in_range(p, __ro_start, __ro_end)) 1540 return p | PTE_P | PTE_NX | cache; 1541 return p | PTE_P | PTE_W | PTE_NX | cache; 1542 } 1543 1544 /* The 2 MiB page holding a, split into 4 KiB pages at the protection 1545 * boundaries above; a no-op when it already is. */ 1546 static void split_2m(uint64_t a) 1547 { 1548 uint64_t *e = &pds[a >> 30][(a >> 21) & 511]; 1549 if (!(*e & PTE_PS)) 1550 return; 1551 uint64_t cache = *e & (PTE_PCD | PTE_PWT), *pt = table_new(); 1552 a &= ~((2ull << 20) - 1); 1553 for (uint64_t j = 0; j < 512; j++) 1554 pt[j] = leaf_4k(a | j << 12, cache); 1555 *e = (uint64_t)(uintptr_t)pt | PTE_P | PTE_W; 1556 } 1557 1558 static uint64_t *pte_4k(uint64_t a) 1559 { 1560 uint64_t e = pds[a >> 30][(a >> 21) & 511]; 1561 return (uint64_t *)(uintptr_t)(e & PTE_ADDR) + ((a >> 12) & 511); 1562 } 1563 1564 /* Lab swap only, called once after a verified payload and before the jump: the 1565 * trampoline page (read-only no-execute once smp_start parks the cores) becomes 1566 * writable and executable again, and so does the running image, which the trampoline 1567 * overwrites with the new kernel's sections (text is read-only and data no-execute 1568 * under W^X; the new kernel runs on these tables until its own mm_build). 1569 * The application processors are halted by then (quiesce_aps), so the BSP's CR3 reload 1570 * is the only TLB flush needed. */ 1571 void ck_x86_swap_tramp_open(void) 1572 { 1573 uint64_t *e = tramp_pa ? pte_4k(tramp_pa) : 0; 1574 if (e) 1575 *e = (*e | PTE_W) & ~PTE_NX; 1576 for (uint64_t a = (uint64_t)(uintptr_t)__image_base; a < (uint64_t)(uintptr_t)__image_end; a += CK_PAGE) { 1577 uint64_t *pd = &pds[a >> 30][(a >> 21) & 511]; 1578 if (!(*pd & PTE_P)) 1579 continue; 1580 if (*pd & PTE_PS) { 1581 *pd = (*pd | PTE_W) & ~PTE_NX; 1582 continue; 1583 } 1584 /* The stack guard (kstack's first page) is unmapped: it is image memory the copy 1585 * writes too, mapped back identity, write-back, like the image pages around it. */ 1586 uint64_t *pte = pte_4k(a); 1587 *pte = (*pte & PTE_P) ? (*pte | PTE_W) & ~PTE_NX : a | PTE_P | PTE_W; 1588 } 1589 ck_wr_cr3(ck_rd_cr3()); 1590 } 1591 1592 /* Memory this kernel is standing on when it starts, kept out of the frame pool. After the 1593 * firmware it all sits outside conventional memory and the reserves change nothing. After a live 1594 * swap (swap_x86.c) the old kernel's frames hold it: the handoff record (in the old kernel's 1595 * trampoline page), the memory map copy, the stack this code runs on, and the page tables CR3 1596 * still points at. A frame handed out from any of them would be overwritten while in use. */ 1597 #define LIVE_STACK_BELOW (16u << 10) /* stack mm_build may still grow into below the current rsp */ 1598 #define LIVE_STACK_ABOVE (64u << 10) /* the callers' frames above it (the swap stack is 64 KiB) */ 1599 static void reserve_live(const struct ck_handoff *h) 1600 { 1601 uint64_t hp = (uint64_t)(uintptr_t)h, rsp; 1602 ck_frames_reserve(&frames, hp, hp + sizeof *h); 1603 ck_frames_reserve(&frames, h->memory_map, h->memory_map + h->map_size); 1604 __asm__ volatile("mov %%rsp, %0" : "=r"(rsp)); 1605 ck_frames_reserve(&frames, rsp > LIVE_STACK_BELOW ? rsp - LIVE_STACK_BELOW : 0, rsp + LIVE_STACK_ABOVE); 1606 /* The firmware's tables are its own memory; any other CR3 is a previous kernel's, built from 1607 * frames: keep every table it reaches (leaves of 1 GiB and 2 MiB are not tables). */ 1608 uint64_t cr3 = ck_rd_cr3() & PTE_ADDR; 1609 if (cr3 == (h->firmware_ttbr0 & PTE_ADDR)) 1610 return; 1611 ck_frames_reserve(&frames, cr3, cr3 + CK_PAGE); 1612 const uint64_t *l4 = (const uint64_t *)(uintptr_t)cr3; 1613 for (unsigned a = 0; a < 512; a++) { 1614 if (!(l4[a] & PTE_P)) 1615 continue; 1616 const uint64_t *l3 = (const uint64_t *)(uintptr_t)(l4[a] & PTE_ADDR); 1617 ck_frames_reserve(&frames, (uint64_t)(uintptr_t)l3, (uint64_t)(uintptr_t)l3 + CK_PAGE); 1618 for (unsigned b = 0; b < 512; b++) { 1619 if (!(l3[b] & PTE_P) || (l3[b] & PTE_PS)) 1620 continue; 1621 const uint64_t *l2 = (const uint64_t *)(uintptr_t)(l3[b] & PTE_ADDR); 1622 ck_frames_reserve(&frames, (uint64_t)(uintptr_t)l2, (uint64_t)(uintptr_t)l2 + CK_PAGE); 1623 for (unsigned c = 0; c < 512; c++) 1624 if ((l2[c] & PTE_P) && !(l2[c] & PTE_PS)) 1625 ck_frames_reserve(&frames, l2[c] & PTE_ADDR, (l2[c] & PTE_ADDR) + CK_PAGE); 1626 } 1627 } 1628 } 1629 1630 static void mm_build(void) 1631 { 1632 const struct ck_handoff *h = hand; 1633 ck_frames_init(&frames); 1634 if (ck_frames_from_efi(&frames, (const void *)(uintptr_t)h->memory_map, h->map_size, h->desc_size) < 0) 1635 ck_panic("memory: bad UEFI memory map"); 1636 /* Page 0 stays out: a null pointer must never be a usable frame. */ 1637 ck_frames_reserve(&frames, 0, CK_PAGE); 1638 /* The running kernel's own image is never a frame. Its pages can be typed conventional in the 1639 * map, and then a frame taken from them (the swap stack did) is inside the image that a live 1640 * swap copies over. Reserving it keeps every frame the kernel hands out outside its image. */ 1641 ck_frames_reserve(&frames, (uint64_t)(uintptr_t)__image_base, (uint64_t)(uintptr_t)__image_end); 1642 reserve_live(h); 1643 /* The secondary-core trampoline needs a page below 1 MiB; take the 1644 * lowest free page before anything else does. */ 1645 if (ck_frames_alloc(&frames, 1, CK_PAGE, &tramp_pa) || tramp_pa >= 0x100000) 1646 tramp_pa = 0; 1647 1648 uint64_t top = 4ull << 30; 1649 for (uint64_t off = 0; off + h->desc_size <= h->map_size; off += h->desc_size) { 1650 const struct ck_efi_desc *d = (const void *)(uintptr_t)(h->memory_map + off); 1651 uint64_t end = d->phys + d->pages * CK_PAGE; 1652 if (end > top) 1653 top = end; 1654 } 1655 top = (top + (1ull << 30) - 1) & ~((1ull << 30) - 1); 1656 if (top > MAP_TOP_MAX) 1657 top = MAP_TOP_MAX; 1658 mm.top = top; 1659 1660 /* Framebuffer: write-combining 2 MiB pages, unless one overlaps RAM. */ 1661 if (h->fb_status == CK_HANDOFF_FB_PRESENT) { 1662 mm.fb_lo = h->fb_base & ~((2ull << 20) - 1); 1663 mm.fb_hi = (h->fb_base + h->fb_size + (2ull << 20) - 1) & ~((2ull << 20) - 1); 1664 mm.fb_ok = mm.fb_hi <= top; 1665 for (uint64_t off = 0; mm.fb_ok && off + h->desc_size <= h->map_size; off += h->desc_size) { 1666 const struct ck_efi_desc *d = (const void *)(uintptr_t)(h->memory_map + off); 1667 uint64_t lo = d->phys, hi = d->phys + d->pages * CK_PAGE; 1668 if (efi_ram(d->type) && lo < mm.fb_hi && hi > mm.fb_lo) 1669 mm.fb_ok = 0; 1670 } 1671 } 1672 1673 /* Every 2 MiB page starts uncached (PCD|PWT, PAT index 3): device memory 1674 * (local APIC, I/O APIC, HPET, PCI BARs) whatever the MTRRs say. Pages 1675 * that hold RAM from the memory map become write-back (index 0), the 1676 * framebuffer write-combining (PWT alone, index 1, set to WC below). 1677 * Every 2 MiB page is no-execute; the ones holding the image or the 1678 * trampoline are split into 4 KiB pages (leaf_4k) after the cache types 1679 * are set. */ 1680 if (ck_rd_cr4() & (1ull << 12)) 1681 ck_panic("paging: firmware runs 5-level paging (CR4.LA57); this kernel builds 4-level tables"); 1682 uint32_t x[4]; 1683 ck_cpuid(0x80000000, 0, x); 1684 if (x[0] < 0x80000001) 1685 ck_panic("paging: no CPUID leaf 0x80000001, so no NX"); 1686 ck_cpuid(0x80000001, 0, x); 1687 if (!(x[3] & (1u << 20))) 1688 ck_panic("paging: CPU has no NX (execute disable); this kernel needs it for W^X"); 1689 uint64_t *pml4 = table_new(), *pdpt = table_new(); 1690 pml4[0] = (uint64_t)(uintptr_t)pdpt | PTE_P | PTE_W; 1691 for (uint64_t g = 0; g < top >> 30; g++) { 1692 uint64_t *pd = pds[g] = table_new(); 1693 pdpt[g] = (uint64_t)(uintptr_t)pd | PTE_P | PTE_W; 1694 for (uint64_t i = 0; i < 512; i++) 1695 pd[i] = (g << 30 | i << 21) | PTE_P | PTE_W | PTE_PS | PTE_PCD | PTE_PWT | PTE_NX; 1696 } 1697 for (uint64_t off = 0; off + h->desc_size <= h->map_size; off += h->desc_size) { 1698 const struct ck_efi_desc *d = (const void *)(uintptr_t)(h->memory_map + off); 1699 if (!efi_ram(d->type)) 1700 continue; 1701 uint64_t hi = d->phys + d->pages * CK_PAGE; 1702 for (uint64_t a = d->phys & ~((2ull << 20) - 1); a < hi && a < top; a += 2ull << 20) { 1703 uint64_t *e = &pds[a >> 30][(a >> 21) & 511]; 1704 if (*e & PTE_PS) 1705 *e &= ~(PTE_PCD | PTE_PWT); 1706 } 1707 } 1708 for (uint64_t a = mm.fb_lo; mm.fb_ok && a < mm.fb_hi; a += 2ull << 20) { 1709 uint64_t *e = &pds[a >> 30][(a >> 21) & 511]; 1710 if (*e & PTE_PS) 1711 *e = (*e & ~PTE_PCD) | PTE_PWT; 1712 } 1713 for (uint64_t a = (uint64_t)(uintptr_t)__image_base & ~((2ull << 20) - 1); a < (uint64_t)(uintptr_t)__image_end; 1714 a += 2ull << 20) 1715 split_2m(a); 1716 split_2m(0); /* page 0 not present */ 1717 if (tramp_pa) 1718 split_2m(tramp_pa); 1719 for (uint64_t g = 0; g < top >> 30; g++) 1720 for (uint64_t i = 0; i < 512; i++) { 1721 uint64_t e = pds[g][i]; 1722 if (!(e & PTE_PS)) 1723 continue; 1724 if (e & PTE_PCD) 1725 mm.pages_uc++; 1726 else if (e & PTE_PWT) 1727 mm.pages_wc++; 1728 else 1729 mm.pages_wb++; 1730 } 1731 mm.root = (uint64_t)(uintptr_t)pml4; 1732 1733 /* IA32_PAT: the power-on value with entry 1 (PWT) changed from WT to WC. */ 1734 uint32_t r[4]; 1735 ck_cpuid(1, 0, r); 1736 if (!(r[3] & (1u << 16))) 1737 ck_panic("paging: CPU has no PAT"); 1738 __asm__ volatile("wbinvd" ::: "memory"); 1739 ck_wrmsr(0x277, 0x0007040600070106ull); 1740 /* NX bits are reserved (every access faults) until EFER.NXE is set; 1741 * CR0.WP makes read-only pages bind the kernel too. */ 1742 ck_wrmsr(MSR_EFER, ck_rdmsr(MSR_EFER) | EFER_NXE); 1743 ck_wr_cr3(mm.root); 1744 __asm__ volatile("mov %0, %%cr0" ::"r"(ck_rd_cr0() | CR0_WP) : "memory"); 1745 /* Toggling CR4.PGE drops global TLB entries the firmware's tables left. */ 1746 uint64_t cr4 = ck_rd_cr4(); 1747 if (cr4 & 0x80) { 1748 __asm__ volatile("mov %0, %%cr4" ::"r"(cr4 & ~0x80ull) : "memory"); 1749 __asm__ volatile("mov %0, %%cr4" ::"r"(cr4) : "memory"); 1750 } 1751 __asm__ volatile("wbinvd" ::: "memory"); 1752 } 1753 1754 /* Device registers above the identity-mapped range (a 64-bit BAR the firmware 1755 * placed high, as OVMF does with NVMe): 2 MiB uncached pages added to the live 1756 * tables on demand. 0 ok, -1 refused (wraps or beyond 46 address bits). */ 1757 static uint64_t *sub_table(uint64_t *t, unsigned i) 1758 { 1759 if (!(t[i] & PTE_P)) 1760 t[i] = (uint64_t)(uintptr_t)table_new() | PTE_P | PTE_W; 1761 return (uint64_t *)(uintptr_t)(t[i] & PTE_ADDR); 1762 } 1763 1764 int ck_x86_map_mmio(uint64_t pa, uint64_t len) 1765 { 1766 if (!len || pa + len < pa || pa + len > (1ull << 46)) 1767 return -1; 1768 uint64_t *pml4 = (uint64_t *)(uintptr_t)mm.root; 1769 for (uint64_t a = pa & ~((2ull << 20) - 1); a < pa + len; a += 2ull << 20) { 1770 if (a < mm.top) 1771 continue; 1772 uint64_t *pd = sub_table(sub_table(pml4, (unsigned)(a >> 39) & 511), (unsigned)(a >> 30) & 511); 1773 uint64_t *e = &pd[(a >> 21) & 511]; 1774 if (!(*e & PTE_P)) { 1775 *e = a | PTE_P | PTE_W | PTE_PS | PTE_PCD | PTE_PWT | PTE_NX; 1776 mm.pages_uc++; 1777 } 1778 /* only not-present entries become present here, and no core caches a 1779 * not-present translation, so the other cores need no shootdown */ 1780 __asm__ volatile("invlpg (%0)" ::"r"(a) : "memory"); 1781 } 1782 return 0; 1783 } 1784 1785 /* ---- time ---- */ 1786 static const char *timebase = "none"; 1787 static uint64_t hpet_period_fs; 1788 1789 static void tsc_measure(void) 1790 { 1791 const uint8_t *t = ck_acpi_lookup(hand->rsdp, "HPET"); 1792 if (t && rd32(t, 4) >= 56 && t[40] == 0) { 1793 volatile uint64_t *hp = (volatile uint64_t *)(uintptr_t)rd64(t, 44); 1794 uint64_t period = hp[0] >> 32; /* GCAP_ID: counter period in fs */ 1795 if (period && period <= 100000000ull) { 1796 hp[2] |= 1; /* GEN_CONF.ENABLE_CNF */ 1797 uint64_t want = 50000000000000ull / period; /* 50 ms in HPET ticks */ 1798 /* Bounded by 2^34 TSC ticks (about 5 s at 3.4 GHz): an HPET that 1799 * does not count falls through to CPUID instead of hanging. */ 1800 uint64_t c0 = hp[30], s0 = ck_rdtsc(), c1; 1801 do 1802 c1 = hp[30]; 1803 while (c1 - c0 < want && ck_rdtsc() - s0 < (1ull << 34)); 1804 if (c1 - c0 < want) 1805 goto no_hpet; 1806 uint64_t s1 = ck_rdtsc(), ns = (c1 - c0) * period / 1000000ull; 1807 if (ns) { 1808 tsc_hz = (s1 - s0) * 1000000000ull / ns; 1809 hpet_period_fs = period; 1810 timebase = "hpet"; 1811 return; 1812 } 1813 } 1814 } 1815 no_hpet:; 1816 uint32_t r[4]; 1817 ck_cpuid(0, 0, r); 1818 if (r[0] >= 0x16) { 1819 ck_cpuid(0x16, 0, r); 1820 if (r[0]) { 1821 tsc_hz = (uint64_t)r[0] * 1000000ull; 1822 timebase = "cpuid16"; 1823 } 1824 } 1825 } 1826 1827 /* ---- interrupts ---- */ 1828 struct apic_report { 1829 uint32_t id, version, lapic_hz, cpus, ioapics, ioapic_lines; 1830 uint64_t ticks, ms, min_us, max_us, avg_us; 1831 }; 1832 1833 static void ioapic_mask_all(uint64_t base, uint32_t *lines) 1834 { 1835 volatile uint32_t *io = (volatile uint32_t *)(uintptr_t)base; 1836 io[0] = 1; 1837 uint32_t n = ((io[4] >> 16) & 0xff) + 1; 1838 for (uint32_t i = 0; i < n; i++) { 1839 io[0] = 0x10 + 2 * i; 1840 io[4] |= 1u << 16; 1841 } 1842 *lines += n; 1843 } 1844 1845 static void madt_walk(struct apic_report *ar) 1846 { 1847 const uint8_t *m = ck_acpi_lookup(hand->rsdp, "APIC"); 1848 if (!m) 1849 ck_panic("madt: no ACPI MADT"); 1850 uint32_t len = rd32(m, 4); 1851 for (uint32_t off = 44; off + 2 <= len;) { 1852 uint8_t type = m[off], el = m[off + 1]; 1853 if (el < 2 || off + el > len) 1854 ck_panic("madt: bad entry at %u", off); 1855 if (type == 0 && el >= 8 && (rd32(m, off + 4) & 3)) 1856 ar->cpus++; 1857 else if (type == 9 && el >= 16 && (rd32(m, off + 8) & 3)) 1858 ar->cpus++; 1859 else if (type == 1 && el >= 12) { 1860 ar->ioapics++; 1861 ioapic_mask_all(rd32(m, off + 4), &ar->ioapic_lines); 1862 } 1863 off += el; 1864 } 1865 } 1866 1867 static void apic_start(struct apic_report *ar) 1868 { 1869 /* Legacy 8259 PICs: every line masked. */ 1870 ck_outb(0x21, 0xff); 1871 ck_outb(0xa1, 0xff); 1872 uint64_t base = ck_rdmsr(0x1b); 1873 if (base & 1u << 10) /* x2APIC on: leaving it needs a pass through disabled */ 1874 ck_wrmsr(0x1b, base & ~(3ull << 10)); 1875 ck_wrmsr(0x1b, (base & ~(1ull << 10)) | 1u << 11); 1876 xapic = (volatile uint32_t *)(uintptr_t)(base & 0xffffff000ull); 1877 ar->id = apic_rd(APIC_ID) >> 24; 1878 ar->version = apic_rd(APIC_VER); 1879 apic_wr(APIC_TPR, 0); 1880 apic_wr(APIC_SVR, 0x100 | VEC_SPURIOUS); 1881 1882 /* LAPIC timer rate: divide by 16, one shot, 10 ms of TSC. */ 1883 apic_wr(APIC_TIMER_DIV, 0x3); 1884 apic_wr(APIC_LVT_TIMER, 1u << 16 | VEC_TIMER); 1885 apic_wr(APIC_TIMER_INIT, 0xffffffffu); 1886 delay_ms(10); 1887 uint32_t left = apic_rd(APIC_TIMER_CUR); 1888 apic_wr(APIC_TIMER_INIT, 0); 1889 ar->lapic_hz = (0xffffffffu - left) * 100u; 1890 if (!ar->lapic_hz) 1891 ck_panic("apic: timer did not count"); 1892 1893 /* 100 Hz periodic for 20 ticks, bounded by 1 s. */ 1894 ticks = 0; 1895 apic_wr(APIC_LVT_TIMER, 1u << 17 | VEC_TIMER); 1896 apic_wr(APIC_TIMER_INIT, ar->lapic_hz / 100u); 1897 uint64_t t0 = ck_rdtsc(); 1898 ck_sti(); 1899 while (ticks < 21 && ck_rdtsc() - t0 < tsc_hz) 1900 ck_pause(); /* not hlt: a timer that never fires must not hang the boot */ 1901 ck_cli(); 1902 apic_wr(APIC_LVT_TIMER, 1u << 16 | VEC_TIMER); 1903 apic_wr(APIC_TIMER_INIT, 0); 1904 uint64_t n = ticks < 21 ? ticks : 21; 1905 ar->ticks = n ? n - 1 : 0; /* intervals between the first and the last tick seen */ 1906 ar->min_us = ~0ull; 1907 for (uint64_t i = 1; i < n; i++) { 1908 uint64_t us = (tick_tsc[i] - tick_tsc[i - 1]) * 1000000ull / tsc_hz; 1909 if (us < ar->min_us) 1910 ar->min_us = us; 1911 if (us > ar->max_us) 1912 ar->max_us = us; 1913 } 1914 if (ar->ticks) { 1915 uint64_t span = (tick_tsc[n - 1] - tick_tsc[0]) * 1000000ull / tsc_hz; 1916 ar->avg_us = span / ar->ticks; 1917 ar->ms = span / 1000; 1918 } else { 1919 ar->min_us = 0; 1920 } 1921 } 1922 1923 /* ---- secondary cores ---- 1924 * Each enabled local APIC the MADT lists (other than this core's) gets INIT, 1925 * SIPI, SIPI pointing at the trampoline (smp_x86.S). A started core loads the 1926 * kernel's GDT (no task register) and IDT, sets the same PAT, enables its 1927 * local APIC, records its APIC ID, turns interrupts on (only IPIs reach it: 1928 * its LVT entries are masked, the I/O APIC lines too), checks in, and runs 1929 * the night's drawing or halts. */ 1930 #define SMP_MAX 16u 1931 #define AP_STACK_PAGES 4u 1932 #define APIC_ICR_LO 0x300 1933 #define APIC_ICR_HI 0x310 1934 #define PAT_VALUE 0x0007040600070106ull 1935 1936 struct smp_report { 1937 unsigned listed, started, failed; 1938 uint32_t ids[SMP_MAX], up_ids[SMP_MAX]; 1939 const char *why; 1940 }; 1941 static volatile uint32_t ap_up, ap_ids[SMP_MAX], ap_nx_wp; /* ap_nx_wp: cores that came up with EFER.NXE and CR0.WP */ 1942 1943 static void delay_us(uint64_t us) 1944 { 1945 uint64_t t0 = ck_rdtsc(), n = tsc_hz / `1000000` * us; 1946 while (ck_rdtsc() - t0 < n) 1947 ck_pause(); 1948 } 1949 1950 static void ap_entry(void *arg) 1951 { 1952 uint64_t idx = (uint64_t)(uintptr_t)arg; 1953 struct dtr g = {sizeof gdt - 1, (uint64_t)(uintptr_t)gdt}; 1954 ck_x86_load_gdt(&g, SEL_CODE, SEL_DATA, 0); 1955 struct dtr i = {sizeof idt - 1, (uint64_t)(uintptr_t)idt}; 1956 __asm__ volatile("lidt %0" ::"m"(i) : "memory"); 1957 ck_wrmsr(0x277, PAT_VALUE); 1958 uint64_t base = ck_rdmsr(0x1b); 1959 if (base & 1u << 10) 1960 ck_wrmsr(0x1b, base & ~(3ull << 10)); 1961 ck_wrmsr(0x1b, (base & ~(1ull << 10)) | 1u << 11); 1962 apic_wr(APIC_TPR, 0); 1963 apic_wr(APIC_SVR, 0x100 | VEC_SPURIOUS); 1964 ap_ids[idx] = apic_rd(APIC_ID) >> 24; 1965 if ((ck_rdmsr(MSR_EFER) & EFER_NXE) && (ck_rd_cr0() & CR0_WP)) 1966 __atomic_fetch_add(&ap_nx_wp, 1, __ATOMIC_SEQ_CST); 1967 __asm__ volatile("sti" ::: "memory"); /* before checking in: a shootdown can come any time after */ 1968 __atomic_fetch_add(&ap_up, 1, __ATOMIC_SEQ_CST); 1969 if (idx == 0) /* the first one draws the night's frames, the next two help */ 1970 draw_loop(); 1971 else if (idx < 3) 1972 help_loop(); 1973 for (;;) 1974 __asm__ volatile("hlt"); 1975 } 1976 1977 static int icr_send(uint32_t id, uint32_t lo) 1978 { 1979 apic_wr(APIC_ICR_HI, id << 24); 1980 apic_wr(APIC_ICR_LO, lo); 1981 for (unsigned n = 0; n < 1000; n++) { 1982 if (!(apic_rd(APIC_ICR_LO) & 1u << 12)) 1983 return 0; 1984 delay_us(1); 1985 } 1986 return -1; 1987 } 1988 1989 /* Lab swap only (swap_x86.c), before the trampoline overwrites this image: every other core 1990 * gets INIT, all excluding self (SDM vol.3 13.4.7.3, broadcast 000C4500H as in 11.4.4.1), and 1991 * waits for a start-up IPI with no code of ours running. A drawing core left in draw_loop would 1992 * run the new kernel's bytes mid-copy. The new kernel starts them again with INIT, SIPI, SIPI. */ 1993 void ck_x86_swap_stop_aps(void) 1994 { 1995 if (!ap_up) 1996 return; 1997 if (icr_send(0, 0xc4500)) 1998 ck_puts("swap: INIT to the other cores not accepted by the local APIC\n"); 1999 delay_ms(10); 2000 ck_printf("swap: %u other cores stopped (INIT, waiting for start-up)\n", (unsigned)ap_up); 2001 } 2002 2003 static void tramp_put32(const char *sym, uint32_t v) 2004 { 2005 uint64_t off = (uint64_t)(uintptr_t)(sym - ck_x86_tramp_start); 2006 memcpy((uint8_t *)(uintptr_t)tramp_pa + off, &v, 4); 2007 } 2008 static void tramp_put64(const char *sym, uint64_t v) 2009 { 2010 uint64_t off = (uint64_t)(uintptr_t)(sym - ck_x86_tramp_start); 2011 memcpy((uint8_t *)(uintptr_t)tramp_pa + off, &v, 8); 2012 } 2013 static uint32_t tramp_at(const char *sym) 2014 { 2015 return (uint32_t)(tramp_pa + (uint64_t)(uintptr_t)(sym - ck_x86_tramp_start)); 2016 } 2017 2018 /* TLB shootdown (#485). invlpg drops a translation from this core's TLB only, 2019 * so a change that takes rights from a page (or unmaps it) is not done until 2020 * every core that may hold the old translation has dropped it too: the page 2021 * is flushed here, VEC_TLB goes to every secondary core that has checked in, 2022 * and this returns once each has flushed it and acknowledged. A core that 2023 * does not answer within a second is a panic, never a page left stale. Only 2024 * the boot core changes page tables, so one request is in flight at a time. */ 2025 static uint32_t tlb_shootdowns, tlb_acked; 2026 static void tlb_flush_page(uint64_t va) 2027 { 2028 __asm__ volatile("invlpg (%0)" ::"r"(va) : "memory"); 2029 #ifndef CK_X86_WX_MUTANT_NO_SHOOTDOWN 2030 uint32_t n = __atomic_load_n(&ap_up, __ATOMIC_ACQUIRE); 2031 if (n > SMP_MAX) 2032 n = SMP_MAX; 2033 if (!n) 2034 return; 2035 tlb_va = va; 2036 __atomic_store_n(&tlb_acks, 0, __ATOMIC_SEQ_CST); 2037 for (uint32_t k = 0; k < n; k++) 2038 if (icr_send(ap_ids[k], 0x4000 | VEC_TLB)) /* fixed, assert */ 2039 ck_panic("tlb: shootdown IPI to core %u not delivered", ap_ids[k]); 2040 uint64_t t0 = ck_rdtsc(); 2041 uint32_t got; 2042 while ((got = __atomic_load_n(&tlb_acks, __ATOMIC_ACQUIRE)) < n) { 2043 if (ck_rdtsc() - t0 > tsc_hz) 2044 ck_panic("tlb: shootdown of 0x%llx acknowledged by %u of %u secondary cores", (unsigned long long)va, 2045 got, n); 2046 ck_pause(); 2047 } 2048 tlb_shootdowns++; 2049 tlb_acked += got; 2050 #endif 2051 } 2052 2053 /* The trampoline page is never writable and executable at once, on any core: 2054 * RW+NX while it is filled, RX while a core runs it, R+NX once the cores are 2055 * started. The cores already started are running and still hold its RX 2056 * translation from their own start, so every change is a shootdown. */ 2057 static void tramp_prot(uint64_t bits) 2058 { 2059 uint64_t *e = pte_4k(tramp_pa); 2060 *e = (*e & (PTE_ADDR | PTE_PCD | PTE_PWT)) | PTE_P | bits; 2061 tlb_flush_page(tramp_pa); 2062 } 2063 2064 static void smp_start(const struct apic_report *ar, struct smp_report *sr) 2065 { 2066 const uint8_t *m = ck_acpi_lookup(hand->rsdp, "APIC"); 2067 uint32_t len = rd32(m, 4); 2068 for (uint32_t off = 44; off + 2 <= len; off += m[off + 1]) 2069 if (m[off] == 0 && m[off + 1] >= 8 && (rd32(m, off + 4) & 3) && sr->listed < SMP_MAX) 2070 sr->ids[sr->listed++] = m[off + 3]; 2071 uint64_t size = (uint64_t)(uintptr_t)(ck_x86_tramp_end - ck_x86_tramp_start); 2072 if (!tramp_pa) 2073 sr->why = "no free page below 1 MiB"; 2074 else if (mm.root >= (1ull << 32)) 2075 sr->why = "page tables above 4 GiB"; 2076 else if (size > CK_PAGE) 2077 sr->why = "trampoline larger than a page"; 2078 if (sr->why) { 2079 if (tramp_pa) 2080 tramp_prot(PTE_NX); 2081 return; 2082 } 2083 memcpy((void *)(uintptr_t)tramp_pa, ck_x86_tramp_start, size); 2084 tramp_put32(ck_x86_tramp_gdtr + 2, tramp_at(ck_x86_tramp_gdt)); 2085 tramp_put32(ck_x86_tramp_far32, tramp_at(ck_x86_tramp_pm32)); 2086 tramp_put32(ck_x86_tramp_far64, tramp_at(ck_x86_tramp_lm64)); 2087 tramp_put32(ck_x86_tramp_cr3, (uint32_t)mm.root); 2088 tramp_put64(ck_x86_tramp_entry, (uint64_t)(uintptr_t)ap_entry); 2089 for (unsigned k = 0; k < sr->listed; k++) { 2090 uint32_t id = sr->ids[k]; 2091 if (id == ar->id) 2092 continue; 2093 uint64_t st; 2094 if (ck_frames_alloc(&frames, AP_STACK_PAGES, CK_PAGE, &st)) { 2095 sr->failed++; 2096 continue; 2097 } 2098 unsigned before = ap_up; 2099 tramp_prot(PTE_W | PTE_NX); 2100 tramp_put64(ck_x86_tramp_stack, st + AP_STACK_PAGES * CK_PAGE); 2101 tramp_put64(ck_x86_tramp_arg, before); 2102 tramp_prot(0); 2103 __asm__ volatile("mfence" ::: "memory"); 2104 int bad = icr_send(id, 0x4500); /* INIT, assert */ 2105 delay_ms(10); 2106 for (unsigned s = 0; s < 2 && ap_up == before; s++) { 2107 bad |= icr_send(id, 0x4600 | (uint32_t)(tramp_pa >> 12)); /* start-up */ 2108 delay_us(200); 2109 } 2110 uint64_t t0 = ck_rdtsc(); 2111 while (ap_up == before && ck_rdtsc() - t0 < tsc_hz / 10) 2112 ck_pause(); 2113 if (ap_up != before && !bad) 2114 sr->up_ids[sr->started++] = ap_ids[before]; 2115 else 2116 sr->failed++; 2117 if (ap_up > before + 1) 2118 break; /* a core checked in twice or out of turn: stop starting more */ 2119 } 2120 tramp_prot(PTE_NX); 2121 } 2122 2123 /* ---- W^X (#409) ---- 2124 * Each probe arms the #PF catcher (ck_x86_trap), touches one address and 2125 * resumes after the access. The store writes back the byte it read, so a 2126 * build that lets it through changes nothing. The execute probe jumps to 2127 * `jmp *%rax` (rax = the resume label), so code that does run comes straight 2128 * back and the probe sees no fault. Error code bits: P 0, W 1, RSVD 3, I/D 4. */ 2129 static int probe_write(uint64_t a) 2130 { 2131 probe.hit = 0; 2132 probe.armed = 1; 2133 __asm__ volatile("lea 1f(%%rip), %%rax\n\t" 2134 "mov %%rax, %0\n\t" 2135 "movb (%1), %%cl\n\t" 2136 "movb %%cl, (%1)\n" 2137 "1:" 2138 : "=m"(probe.resume) 2139 : "r"(a) 2140 : "rax", "rcx", "memory"); 2141 probe.armed = 0; 2142 return probe.hit && probe.cr2 == a && (probe.err & 0x1b) == 0x03; 2143 } 2144 2145 static int probe_exec(uint8_t *buf) 2146 { 2147 buf[0] = 0xff; /* jmp *%rax */ 2148 buf[1] = 0xe0; 2149 uint64_t a = (uint64_t)(uintptr_t)buf; 2150 probe.hit = 0; 2151 probe.armed = 1; 2152 __asm__ volatile("lea 1f(%%rip), %%rax\n\t" 2153 "mov %%rax, %0\n\t" 2154 "jmp *%1\n" 2155 "1:" 2156 : "=m"(probe.resume) 2157 : "r"(a) 2158 : "rax", "memory"); 2159 probe.armed = 0; 2160 return probe.hit && probe.cr2 == a && (probe.err & 0x1b) == 0x11; 2161 } 2162 2163 static int probe_read(uint64_t a) 2164 { 2165 probe.hit = 0; 2166 probe.armed = 1; 2167 __asm__ volatile("lea 1f(%%rip), %%rax\n\t" 2168 "mov %%rax, %0\n\t" 2169 "movb (%1), %%al\n" 2170 "1:" 2171 : "=m"(probe.resume) 2172 : "r"(a) 2173 : "rax", "memory"); 2174 probe.armed = 0; 2175 return probe.hit && probe.cr2 == a && !(probe.err & 1); 2176 } 2177 2178 /* ---- TLB shootdown self-test (#485) ---- 2179 * On each secondary core in turn: the core writes tlb_page (so it caches a 2180 * writable translation), the boot core makes the page read-only and shoots 2181 * it down, and the core's next write must fault; the core reads the page 2182 * (a fresh read-only translation), the boot core unmaps it and shoots it 2183 * down, and the core's next read must fault. Between its accesses the core 2184 * waits inside the VEC_TLB_PROBE handler with interrupts on and touches 2185 * nothing else, so a translation the shootdown missed is still in its TLB 2186 * and the access goes through. */ 2187 static uint8_t tlb_page[CK_PAGE] __attribute__((aligned(CK_PAGE))); 2188 static volatile uint32_t tlb_step, tlb_faults; /* tlb_faults: bit 0 the write faulted, bit 1 the read */ 2189 2190 static void tlb_probe_run(void) 2191 { 2192 uint64_t a = (uint64_t)(uintptr_t)tlb_page; 2193 __asm__ volatile("sti" ::: "memory"); 2194 *(volatile uint8_t *)tlb_page = 1; 2195 __atomic_store_n(&tlb_step, 1, __ATOMIC_RELEASE); 2196 while (__atomic_load_n(&tlb_step, __ATOMIC_ACQUIRE) != 2) 2197 ck_pause(); 2198 uint32_t got = (uint32_t)probe_write(a); 2199 (void)*(volatile uint8_t *)tlb_page; 2200 __atomic_store_n(&tlb_step, 3, __ATOMIC_RELEASE); 2201 while (__atomic_load_n(&tlb_step, __ATOMIC_ACQUIRE) != 4) 2202 ck_pause(); 2203 got |= (uint32_t)probe_read(a) << 1; 2204 __asm__ volatile("cli" ::: "memory"); 2205 tlb_faults = got; 2206 __atomic_store_n(&tlb_step, 5, __ATOMIC_RELEASE); 2207 } 2208 2209 static void tlb_wait(uint32_t s, uint32_t id) 2210 { 2211 uint64_t t0 = ck_rdtsc(); 2212 while (__atomic_load_n(&tlb_step, __ATOMIC_ACQUIRE) != s) { 2213 if (ck_rdtsc() - t0 > tsc_hz) 2214 ck_panic("tlb_shootdown: core %u stopped before step %u", id, s); 2215 ck_pause(); 2216 } 2217 } 2218 2219 static void tlb_selftest(void) 2220 { 2221 uint32_t n = __atomic_load_n(&ap_up, __ATOMIC_ACQUIRE), stale_w = 0, stale_r = 0; 2222 if (n > SMP_MAX) 2223 n = SMP_MAX; 2224 uint64_t a = (uint64_t)(uintptr_t)tlb_page, *e = pte_4k(a), rw = *e; 2225 for (uint32_t k = 0; k < n; k++) { 2226 uint32_t id = ap_ids[k]; 2227 __atomic_store_n(&tlb_step, 0, __ATOMIC_SEQ_CST); 2228 if (icr_send(id, 0x4000 | VEC_TLB_PROBE)) /* fixed, assert */ 2229 ck_panic("tlb_shootdown: probe IPI to core %u not delivered", id); 2230 tlb_wait(1, id); 2231 *e = rw & ~PTE_W; 2232 tlb_flush_page(a); 2233 __atomic_store_n(&tlb_step, 2, __ATOMIC_RELEASE); 2234 tlb_wait(3, id); 2235 *e = 0; 2236 tlb_flush_page(a); 2237 __atomic_store_n(&tlb_step, 4, __ATOMIC_RELEASE); 2238 tlb_wait(5, id); 2239 *e = rw; 2240 tlb_flush_page(a); 2241 stale_w += !(tlb_faults & 1); 2242 stale_r += !(tlb_faults & 2); 2243 } 2244 if (stale_w || stale_r) 2245 ck_panic("tlb_shootdown: FAIL cores=%u stale_write_allowed=%u stale_read_allowed=%u", n, stale_w, stale_r); 2246 ck_printf("tlb_shootdown: ok cores=%u stale_write_allowed=0 stale_read_allowed=0 shootdowns=%u acks=%u\n", n, 2247 tlb_shootdowns, tlb_acked); 2248 } 2249 2250 static void wx_probes(void) 2251 { 2252 uint64_t efer = ck_rdmsr(MSR_EFER), cr0 = ck_rd_cr0(); 2253 uint8_t *hb = ck_heap_alloc(&heap, 16); 2254 uint8_t sb[16]; 2255 if (!hb) 2256 ck_panic("wx: no heap for the execute probe"); 2257 int tw = probe_write((uint64_t)(uintptr_t)__text_start), rw = probe_write((uint64_t)(uintptr_t)__ro_start); 2258 int hx = probe_exec(hb), sx = probe_exec(sb); 2259 ck_heap_free(&heap, hb); 2260 const char *f = "fault", *n = "ALLOWED"; 2261 if (!(efer & EFER_NXE) || !(cr0 & CR0_WP) || !tw || !rw || !hx || !sx) 2262 ck_panic("wx: FAIL nx=%s wp=%s text_write=%s ro_write=%s heap_exec=%s stack_exec=%s", 2263 efer & EFER_NXE ? "on" : "off", cr0 & CR0_WP ? "on" : "off", tw ? f : n, rw ? f : n, 2264 hx ? f : n, sx ? f : n); 2265 ck_puts("wx: ok nx=on wp=on text_write=fault ro_write=fault heap_exec=fault stack_exec=fault\n"); 2266 } 2267 2268 /* Every present leaf of the live tables (identity map, MMIO above it, the 2269 * trampoline): no page may be writable and executable, the executable ones 2270 * must be exactly the code, and the PE header and read-only data must not 2271 * be writable. Counts are 4 KiB pages. */ 2272 static void wx_audit(unsigned started) 2273 { 2274 uint64_t wx = 0, ex = 0, ex_out = 0, ro_w = 0, text = (uint64_t)(__text_end - __text_start) >> 12; 2275 const uint64_t *pml4 = (const uint64_t *)(uintptr_t)mm.root; 2276 for (uint64_t i = 0; i < 512; i++) { 2277 if (!(pml4[i] & PTE_P)) 2278 continue; 2279 const uint64_t *pdpt = (const uint64_t *)(uintptr_t)(pml4[i] & PTE_ADDR); 2280 for (uint64_t j = 0; j < 512; j++) { 2281 if (!(pdpt[j] & PTE_P)) 2282 continue; 2283 if (pdpt[j] & PTE_PS) { /* 1 GiB page: never built here, counted if present */ 2284 if (!(pdpt[j] & PTE_XD)) { 2285 ex += 1u << 18, ex_out += 1u << 18; 2286 wx += pdpt[j] & PTE_W ? 1u << 18 : 0; 2287 } 2288 continue; 2289 } 2290 const uint64_t *pd = (const uint64_t *)(uintptr_t)(pdpt[j] & PTE_ADDR); 2291 for (uint64_t k = 0; k < 512; k++) { 2292 uint64_t e = pd[k]; 2293 if (!(e & PTE_P)) 2294 continue; 2295 if (e & PTE_PS) { 2296 if (!(e & PTE_XD)) { 2297 ex += 512, ex_out += 512; 2298 wx += e & PTE_W ? 512 : 0; 2299 } 2300 continue; 2301 } 2302 const uint64_t *pt = (const uint64_t *)(uintptr_t)(e & PTE_ADDR); 2303 for (uint64_t l = 0; l < 512; l++) { 2304 uint64_t p = i << 39 | j << 30 | k << 21 | l << 12; 2305 if (!(pt[l] & PTE_P)) 2306 continue; 2307 if ((pt[l] & PTE_W) && (in_range(p, __image_base, __text_start) || in_range(p, __ro_start, __ro_end))) 2308 ro_w++; 2309 if (pt[l] & PTE_XD) 2310 continue; 2311 ex++; 2312 ex_out += !in_range(p, __text_start, __text_end); 2313 wx += !!(pt[l] & PTE_W); 2314 } 2315 } 2316 } 2317 } 2318 if (wx || ex != text || ex_out || ro_w || ap_nx_wp != started) 2319 ck_panic("wx_audit: FAIL wx_pages=%llu exec_pages=%llu text_pages=%llu exec_outside_text=%llu ro_writable=%llu " 2320 "cores_nx_wp=%u/%u", 2321 (unsigned long long)wx, (unsigned long long)ex, (unsigned long long)text, 2322 (unsigned long long)ex_out, (unsigned long long)ro_w, ap_nx_wp + 1, started + 1); 2323 ck_printf("wx_audit: ok wx_pages=0 exec_pages=%llu text_pages=%llu exec_outside_text=0 ro_writable=0 " 2324 "cores_nx_wp=%u/%u trampoline=%s\n", 2325 (unsigned long long)ex, (unsigned long long)text, ap_nx_wp + 1, started + 1, 2326 tramp_pa ? "retired" : "none"); 2327 } 2328 2329 /* ---- the kernel ---- */ 2330 static void cpu_line(void) 2331 { 2332 uint32_t r[4]; 2333 char vendor[13], brand[49]; 2334 ck_cpuid(0, 0, r); 2335 memcpy(vendor, &r[1], 4); 2336 memcpy(vendor + 4, &r[3], 4); 2337 memcpy(vendor + 8, &r[2], 4); 2338 vendor[12] = 0; 2339 brand[0] = 0; 2340 ck_cpuid(0x80000000, 0, r); 2341 if (r[0] >= 0x80000004) { 2342 for (uint32_t i = 0; i < 3; i++) { 2343 ck_cpuid(0x80000002 + i, 0, r); 2344 memcpy(brand + 16 * i, r, 16); 2345 } 2346 brand[48] = 0; 2347 } 2348 const char *b = brand; 2349 while (*b == ' ') 2350 b++; 2351 ck_printf("cpu: %s %s\n", vendor, b); 2352 } 2353 2354 /* The night begins before anything is said on the screen; the text stays 2355 * off it (still in the RAM copy and on COM1) until Allen's window takes 2356 * over, or comes back if anything goes wrong. */ 2357 /* ---- real-time clock (CMOS RTC, I/O ports 0x70/0x71) ---- 2358 * Port 0x70: write the register index (bit 7 set disables NMI during read); 2359 * port 0x71: read the value. Reference: Intel 82801 ICH7 datasheet, section 5.7; 2360 * PC/AT BIOS Technical Reference, IBM 1984. */ 2361 static uint8_t cmos_read(uint8_t reg) 2362 { 2363 ck_outb(0x70, (uint8_t)(0x80u | reg)); 2364 return ck_inb(0x71); 2365 } 2366 static uint8_t bcd2bin(uint8_t v) { return (uint8_t)((v >> 4) * 10 + (v & 0xf)); } 2367 /* Read the CMOS RTC and return seconds since 1970-01-01 00:00:00 UTC. 2368 * The iMac's EFI sets the RTC to UTC. Returns 0 if the RTC is unreadable. */ 2369 static int64_t rtc_unix(void) 2370 { 2371 for (int n = 0; n < 100000; n++) /* wait for UIP bit (reg 0x0A bit 7) to clear */ 2372 if (!(cmos_read(0x0a) & 0x80)) 2373 break; 2374 uint8_t s = cmos_read(0x00); uint8_t mi = cmos_read(0x02); uint8_t hr = cmos_read(0x04); 2375 uint8_t dm = cmos_read(0x07); uint8_t mo = cmos_read(0x08); uint8_t yr = cmos_read(0x09); 2376 uint8_t sb = cmos_read(0x0b); uint8_t ce = cmos_read(0x32); 2377 if (s == 0xff && mi == 0xff && hr == 0xff) return 0; 2378 if (!(sb & 0x04)) { /* BCD mode */ 2379 s=bcd2bin(s); mi=bcd2bin(mi); hr=bcd2bin(hr); 2380 dm=bcd2bin(dm); mo=bcd2bin(mo); yr=bcd2bin(yr); ce=bcd2bin(ce); 2381 } 2382 if (!(sb & 0x02) && (hr & 0x80)) { hr = (uint8_t)((hr & 0x7f) + 12); if (hr >= 24) hr -= 12; } 2383 uint32_t year = yr + ((ce >= 19 && ce <= 22) ? (uint32_t)ce * 100u : 2000u); 2384 if (year < 2000) year += 2000; 2385 ck_printf("rtc: %04u-%02u-%02u %02u:%02u:%02u UTC\n", 2386 (unsigned)year, (unsigned)mo, (unsigned)dm, (unsigned)hr, (unsigned)mi, (unsigned)s); 2387 static const uint32_t dbm[13] = {0,0,31,59,90,120,151,181,212,243,273,304,334}; 2388 int leap = (year%4==0 && (year%100!=0 || year%400==0)); 2389 uint32_t doy = dbm[mo] + (uint32_t)dm - 1u + (mo > 2 && leap ? 1u : 0u); 2390 uint32_t y = year - 1; 2391 uint32_t de = (year-1970)*365u + y/4 - y/100 + y/400 - (1969/4 - 1969/100 + 1969/400) + doy; 2392 return (int64_t)de * 86400ll + hr*3600 + mi*60 + s; 2393 } 2394 2395 static void night_start(const struct ck_handoff *h) 2396 { 2397 if (h->fb_status != CK_HANDOFF_FB_PRESENT || !mm.fb_ok || !tsc_hz) 2398 return; 2399 size_t need = ck_allen_ui_mem_bytes(h->fb_width, h->fb_height); 2400 uint64_t pages = (need + CK_PAGE - 1) / CK_PAGE, pa; 2401 if (ck_frames_alloc(&frames, pages, CK_PAGE, &pa)) 2402 return; 2403 uint64_t t0 = ck_rdtsc(); 2404 if (ck_allen_ui_start((volatile uint32_t *)(uintptr_t)h->fb_base, h->fb_width, h->fb_height, h->fb_pitch, 2405 h->fb_format, (void *)(uintptr_t)pa, pages * CK_PAGE, tsc_hz, t0, night_clock)) { 2406 ck_frames_free(&frames, pa, pages); 2407 return; 2408 } 2409 night_t0 = t0; 2410 night_ms = (uint32_t)((ck_rdtsc() - t0) * 1000 / tsc_hz); 2411 night_mib = (uint32_t)(need >> 20); 2412 draw_run = 1; 2413 ck_x86_console_fb_hold(night_tick); 2414 } 2415 2416 static __attribute__((noreturn)) void kernel_main(void *arg) 2417 { 2418 (void)arg; 2419 const struct ck_handoff *h = hand; 2420 tsc_measure(); /* first: the night runs on this clock */ 2421 ck_x86_step("clock"); 2422 night_start(h); 2423 ck_x86_step("night"); 2424 if (h->fb_status == CK_HANDOFF_FB_PRESENT && mm.fb_ok) { 2425 uint32_t scale, cols, rows; 2426 if (ck_x86_console_fb_on((volatile void *)(uintptr_t)h->fb_base, h->fb_width, h->fb_height, 2427 h->fb_pitch, h->fb_format, &scale, &cols, &rows) == 0) 2428 ck_printf("screen: gop %ux%u pitch=%u format=%s base=0x%llx map=wc scale=%u grid=%ux%u\n", 2429 h->fb_width, h->fb_height, h->fb_pitch, h->fb_format ? "bgrx" : "rgbx", 2430 (unsigned long long)h->fb_base, scale, cols, rows); 2431 else 2432 ck_puts("screen: refused (unusable geometry)\n"); 2433 if (draw_run) 2434 ck_printf("screen: night: the sky made in %u ms (%u MiB drawing memory); stars, black holes, then Allen\n", 2435 night_ms, night_mib); 2436 } else if (h->fb_status == CK_HANDOFF_FB_PRESENT) { 2437 ck_puts("screen: refused (framebuffer overlaps RAM or lies above the mapped range)\n"); 2438 } else { 2439 ck_puts("screen: none\n"); 2440 } 2441 uint64_t cr3 = ck_rd_cr3() & PTE_ADDR; 2442 ck_printf("paging: root=0x%llx firmware_cr3=0x%llx switched=%s top_gib=%llu pages_2m_wb=%llu " 2443 "pages_2m_wc=%llu pages_2m_uc=%llu pt_frames=%llu fb=%s pat1=wc\n", 2444 (unsigned long long)cr3, (unsigned long long)(h->firmware_ttbr0 & PTE_ADDR), 2445 cr3 == mm.root && cr3 != (h->firmware_ttbr0 & PTE_ADDR) ? "yes" : "no", 2446 (unsigned long long)(mm.top >> 30), (unsigned long long)mm.pages_wb, (unsigned long long)mm.pages_wc, (unsigned long long)mm.pages_uc, 2447 (unsigned long long)mm.pt_frames, mm.fb_ok ? "wc" : "unmapped"); 2448 2449 uint64_t hp; 2450 if (ck_frames_alloc(&frames, HEAP_PAGES, CK_PAGE, &hp) || 2451 ck_heap_init(&heap, (void *)(uintptr_t)hp, HEAP_PAGES * CK_PAGE)) 2452 ck_panic("heap: no region"); 2453 void *a = ck_heap_alloc(&heap, 100), *b = ck_heap_alloc(&heap, 5000); 2454 if (!a || !b || ck_heap_free(&heap, a) || ck_heap_free(&heap, b) || ck_heap_check(&heap)) 2455 ck_panic("heap: smoke test failed"); 2456 ck_printf("memory: frame_ranges=%u free_bytes=%llu heap=0x%llx+%u heap_test=ok\n", frames.n, 2457 (unsigned long long)ck_frames_free_bytes(&frames), (unsigned long long)hp, 2458 (unsigned)(HEAP_PAGES * CK_PAGE)); 2459 uint64_t ram = 0; 2460 for (uint64_t off = 0; off + hand->desc_size <= hand->map_size; off += hand->desc_size) { 2461 const struct ck_efi_desc *d = (const void *)(uintptr_t)(hand->memory_map + off); 2462 if (efi_ram(d->type)) 2463 ram += d->pages * CK_PAGE; 2464 } 2465 ram_bytes = ram; 2466 /* the firmware keeps a little for itself, so whole GiB rounded up is what is fitted */ 2467 ck_printf("ram: %llu MiB in the memory map, about %llu GiB fitted\n", (unsigned long long)(ram >> 20), 2468 (unsigned long long)((ram + (1ull << 30) - 1) >> 30)); 2469 ck_printf("stack: 0x%llx-0x%llx guard=0x%llx ist1=0x%llx\n", 2470 (unsigned long long)(uintptr_t)(kstack + 4096), 2471 (unsigned long long)(uintptr_t)(kstack + sizeof kstack), (unsigned long long)(uintptr_t)kstack, 2472 (unsigned long long)(uintptr_t)(ist_stack + sizeof ist_stack)); 2473 2474 /* The guard page faults, and the fault is contained. */ 2475 uint64_t g = (uint64_t)(uintptr_t)kstack; 2476 if (probe_read(g)) 2477 ck_printf("guard_page: ok fault=contained (#PF cr2=0x%llx error=0x%llx, not present)\n", 2478 (unsigned long long)probe.cr2, (unsigned long long)probe.err); 2479 else 2480 ck_panic("guard_page: FAIL hit=%d cr2=0x%llx error=0x%llx", probe.hit, (unsigned long long)probe.cr2, 2481 (unsigned long long)probe.err); 2482 /* Physical page 0 is not mapped (#487): a NULL read and a NULL write each 2483 * fault (not present), and the fault is contained. */ 2484 uint64_t null_err[2] = {0, 0}; 2485 int null_ok[2] = {0, 0}; 2486 for (int w = 0; w < 2; w++) { 2487 probe.hit = 0; 2488 probe.armed = 1; 2489 if (w) 2490 __asm__ volatile("lea 1f(%%rip), %%rax\n\t" 2491 "mov %%rax, %0\n\t" 2492 "movb $0, (%1)\n" 2493 "1:" 2494 : "=m"(probe.resume) 2495 : "r"((uint64_t)0) 2496 : "rax", "memory"); 2497 else 2498 __asm__ volatile("lea 1f(%%rip), %%rax\n\t" 2499 "mov %%rax, %0\n\t" 2500 "movb (%1), %%al\n" 2501 "1:" 2502 : "=m"(probe.resume) 2503 : "r"((uint64_t)0) 2504 : "rax", "memory"); 2505 probe.armed = 0; 2506 null_err[w] = probe.err; 2507 null_ok[w] = probe.hit && probe.cr2 == 0 && (probe.err & 0x1b) == (w ? 0x02u : 0x00u); 2508 } 2509 if (null_ok[0] && null_ok[1]) 2510 ck_printf("null_page: ok read=fault write=fault (#PF cr2=0x0 error=0x%llx,0x%llx, not present)\n", 2511 (unsigned long long)null_err[0], (unsigned long long)null_err[1]); 2512 else 2513 ck_panic("null_page: FAIL read=%s write=%s", null_ok[0] ? "fault" : "ALLOWED", null_ok[1] ? "fault" : "ALLOWED"); 2514 wx_probes(); 2515 2516 if (!tsc_hz) 2517 ck_panic("timebase: no HPET and no CPUID leaf 0x16 frequency"); 2518 ck_printf("timebase: %s period_fs=%llu tsc_hz=%llu\n", timebase, (unsigned long long)hpet_period_fs, 2519 (unsigned long long)tsc_hz); 2520 2521 struct apic_report ar = {0}; 2522 madt_walk(&ar); 2523 apic_start(&ar); 2524 ck_x86_step("timer"); 2525 ck_printf("apic: mode=%s id=%u version=0x%x timer_hz=%u\n", "xapic", ar.id, 2526 ar.version, ar.lapic_hz); 2527 ck_printf("madt: cpus=%u ioapics=%u ioapic_lines_masked=%u\n", ar.cpus, ar.ioapics, ar.ioapic_lines); 2528 ck_printf("timer_irq: %llu ticks in %llu ms\n", (unsigned long long)ar.ticks, (unsigned long long)ar.ms); 2529 ck_printf("timer_stats: vector=0x%x period_us=10000 min_us=%llu avg_us=%llu max_us=%llu stray_irqs=%llu\n", 2530 VEC_TIMER, (unsigned long long)ar.min_us, (unsigned long long)ar.avg_us, 2531 (unsigned long long)ar.max_us, (unsigned long long)stray_irqs); 2532 if (ar.ticks < 20) 2533 ck_panic("timer: only %llu ticks", (unsigned long long)ar.ticks); 2534 rest_probe(ar.lapic_hz); 2535 2536 struct smp_report sr = {0}; 2537 smp_start(&ar, &sr); 2538 ck_x86_step("cores"); 2539 if (sr.why) { 2540 ck_printf("smp: cpus=%u started=0 (%s)\n", sr.listed, sr.why); 2541 } else { 2542 char ids[SMP_MAX * 4 + 1]; 2543 unsigned n = 0; 2544 for (unsigned k = 0; k < sr.started; k++) 2545 n += (unsigned)ck_snprintf(ids + n, sizeof ids - n, k ? ",%u" : "%u", sr.up_ids[k]); 2546 ids[n] = 0; 2547 ck_printf("smp: cpus=%u started=%u failed=%u bsp_id=%u ap_ids=%s trampoline=0x%llx state=%s helpers=%u\n", 2548 sr.listed, sr.started, sr.failed, ar.id, sr.started ? ids : "none", 2549 (unsigned long long)tramp_pa, draw_on ? "drawing" : "halted", draw_helpers); 2550 } 2551 tlb_selftest(); 2552 2553 const struct ck_x86_storage_result *st = ck_x86_storage(h->rsdp, &frames, tsc_hz, mm.top); 2554 ck_x86_sound(&frames, tsc_hz, night_t0); /* before the keyboard: the chirp is already under way */ 2555 ck_x86_step("sound"); 2556 ck_x86_usb(&frames, tsc_hz); 2557 ck_x86_step("usb"); 2558 { /* the display chip whose VRAM holds the framebuffer: panel_x86.c may switch its panel while Allen rests */ 2559 volatile uint32_t *px; 2560 uint32_t w, h, pitch, format; 2561 if (ck_x86_console_fb_get(&px, &w, &h, &pitch, &format) == 0) 2562 ck_x86_display((uint64_t)(uintptr_t)px, (uint64_t)pitch * 4u * h, &frames, tsc_hz); 2563 else 2564 ck_x86_display(0, 0, &frames, tsc_hz); 2565 } 2566 ck_x86_swap_init(&frames); 2567 ck_local_init(mm.root, tsc_hz); 2568 ck_local_snapshot(sr.started + 1, ck_frames_free_bytes(&frames), h->fb_width, h->fb_height, st->net_link); 2569 ck_local_selftest(); 2570 allen_facts.cores = sr.started + 1; 2571 allen_facts.sata_disks = st->ahci_disks; 2572 allen_facts.nvme_disks = st->nvme_disks; 2573 ck_printf("AIENOS-KERNEL-0 commit=%s\n", ck_commit()); 2574 wx_audit(sr.started); 2575 ck_puts("kernel: alive\n"); 2576 ck_printf("summary: cores=%u/%u timer=ok sata_disks=%u nvme_disks=%u gpt_valid=%u writes=none net=%s\n", 2577 sr.started + 1, sr.listed, st->ahci_disks, st->nvme_disks, st->gpt_valid, 2578 !st->net_found ? "none" 2579 : st->net_driver == 2 ? "driver-failed" 2580 : st->net_link == 1 ? "link-up" 2581 : st->net_link == 2 ? "link-down" 2582 : st->net_link == 3 ? "link-pending" 2583 : "seen"); 2584 ck_puts("AIENOS-KERNEL-0 DONE\n"); 2585 ck_puts("note: QEMU qualifies nothing physical\n"); 2586 finish(); 2587 } 2588 2589 void ck_x86_kernel_entry(struct ck_handoff *h) 2590 { 2591 ck_cli(); 2592 hand = h; 2593 tables_load(); 2594 ck_puts("\nreport_kind: kernel\n"); 2595 #if defined(CK_X86_WX_MUTANT_NO_NX) || defined(CK_X86_WX_MUTANT_TEXT_RW) || defined(CK_X86_WX_MUTANT_AP_NO_WP) || \ 2596 defined(CK_X86_WX_MUTANT_NO_SHOOTDOWN) 2597 ck_puts("wx: TEST-ONLY W^X mutant build, page permissions deliberately broken, never deploy\n"); 2598 #endif 2599 ck_printf("exit_boot_services: ok attempts=%u\n", h->exit_attempts); 2600 cpu_line(); 2601 ck_puts("descriptors: gdt=7 tss=yes ist1=df,nmi,mc idt=256\n"); 2602 const char *why; 2603 if (ck_handoff_check(h, &why) != 0) 2604 ck_panic("handoff: %s", why); 2605 ck_puts("handoff: CHANDOF3 ok\n"); 2606 mm_build(); 2607 ck_x86_step("paging"); 2608 ck_x86_call_on_stack(kernel_main, 0, (uint64_t)(uintptr_t)(kstack + sizeof kstack)); 2609 }