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/patches/8ed63c055cb52d36 # 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 ## GitHub aien-dev/aienux#421 (code only) closed derived `8ed63c055cb52d36` #421 Imported from GitHub aien-dev/aienux#421 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `47e5c4b58b8026fcd9511a04ce3f7ac7b812aa8a` · Head `644630aec5b5a374786c56f43bd6aa81e44da1cf` drakestapleton reviewed (COMMENTED) on 2026-10-30 11:18 UTC Triage: stale (stacked on #418 `feat/imac-bootdisk`; no activity since 2026-10-18) - The `AIEN Verification` check fails on head `66bf338d`. - In the xHCI re-enumeration in `x86/xhci_x86.c`, check the slot and endpoint teardown on unplug (Disable Slot, then reuse) for stale DMA or transfer-ring use-after-free. - Appears consolidated into #473. - Hardware: needs an iMac serial log of unplug and replug (`keyboard: unplugged`, then the keyboard ready again). To be merge-ready: land the stack below it, fix verification and attach evidence. drakestapleton wrote on 2026-10-18 11:38 UTC ## Ultrareview findings (cloud review, 2026-10-18) and fixes The review could not post its own comment (GitHub rate limit), so here it is by hand, with what changed. # Finding Fix 1 After a failed rediscovery `x.stopped=1, x.rescan=0` and nothing looked again: keyboard dead until reboot. `kbd_rescan` retries up to `KBD_ERR_MAX` (3) times, then waits for a real connect change; while stopped, `ck_x86_kbd_hold_poll` still drains events and sweeps every root port for CSC. 2 Goodbye now sleeps instead of S5, but `qemu_ck_allen_memory_test.sh` and `qemu_ck_imac_bootdisk_test.sh` still waited 300 s for a power-off. Both scripts wait for `power: Allen asleep`, then stop QEMU; checks renamed. 3 After a successful replug `while (ev_next(ev));` swallowed every event, including a transfer completion, so `arm()` never ran again. The drain re-arms when it consumes a transfer event for the keyboard's slot/endpoint. 4 Any failed report triggered an unbounded reset-and-re-enumerate loop while the keyboard stayed plugged in. `x.errors` counts failed reports and failed rediscoveries since the last good report or real (un)plug; past the limit it prints `keyboard: gave up after N tries; unplug it and plug it back in` once and waits for CSC. 5 Texts still said goodbye ends the session or turns the computer off. kmain serial line, Allen's `help` and `good night` replies and the report_x86.c comment now describe sleep plus the 4 s power-button hold. 6 Only the keyboard's original root port was watched; a keyboard moved to another socket was never found. While stopped, port events and the PORTSC sweep cover every root port; `scan_ports` already tries each occupied port. 7 Sleep mark radius passed `S(6)` to `ck_glow`, which takes 1/16 px: one dim pixel. `S(6) * 16`; the host test now requires more than one lit sample. 8 `keyboard: ready (...)` line and decoder reset duplicated in start and rescan. Shared `kbd_ready()`. Verification: host UI test 66 checks PASS; QEMU gates (keyboard, Allen memory, boot disk, kernel with the new microphone checks) listed in the fix commit. ### Fetch it A git bundle of the pull request's head, 219129 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aienux/patches/8ed63c055cb52d36.bundle -o 8ed63c055cb52d36.bundle git fetch 8ed63c055cb52d36.bundle refs/pull/421/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 421 644630aec5b5a374786c56f43bd6aa81e44da1cf ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":421,"url":"https://github.com/aien-dev/aienux/pull/421","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:24Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 81e5c762..03ae3e60 100644 --- a/.crumb +++ b/.crumb @@ -22,7 +22,7 @@ "children": [ { "digest": "b7d58d76e7dacaa887051e8c2d64e2eaef683c9ba82c03e073002f6ddd920239", - "last_commit": "801b248", + "last_commit": "45d8f79", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, @@ -33,14 +33,14 @@ "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "1d869fc8837e95da35cbe14cd535f5c023ab536fead815845eb8d2c4784bcb4a", - "last_commit": "e4bc7aa", + "digest": "0660522029d1706b495ea85da3194a9bcad5d7938241850f23920cd513f1b46d", + "last_commit": "b4c351e", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "5b000b2f77cd62ae8ad2a113a1f77e486e3c974ad5ecc89150e6e54ad714a781", - "last_commit": "e4bc7aa", + "digest": "26606d0e8c4950a8c3c6e095c1420389acb5a4a1147b16b98c282db4c227d037", + "last_commit": "b4c351e", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." }, @@ -51,15 +51,15 @@ "purpose": "First-party host artifact preparation tools" } ], - "children_root": "sha256:200759cfb94b5906e7a16e2317f48eae785ebf45d27cfabadb93828392c3e8d1", - "compiled_at": "2026-10-31T03:50:47Z", + "children_root": "sha256:6bff61a659f1d6cfabc6ed7b237f02e998a6a134d21ece5aaa50af71fd3ab6ad", + "compiled_at": "2026-10-31T03:56:20Z", "compiler": "crumb-compile/1", - "digest": "sha256:6be266506bf9feacc5a140eaea5e549940dbdc8c1d81759c9fa963c9e24424d3", + "digest": "sha256:66341791f683dae8f96d7aacc1842c249981f31ea4c2195997b827b43e18f3d9", "evidence_files": 274, "evidence_root": "sha256:af014a4ed8f6fe759fc5809807fb47578d3410811b522d9f65d749382b029802", "files": 3729, - "generated_at_commit": "b9580267ad8852e8f81391addf20fdd244b91a00", - "source_tree": "sha256:8c6c1135b597a8c2115be3c5b54ad42562d3e56b727e63a91e2ea668c9edc89b" + "generated_at_commit": "b4c351e7bc9c01e9384c19e9d6fc2ab4d2472e85", + "source_tree": "sha256:07c799c6a9a44467b36b39c4e9994e3bdd6417e0f726088b621e03b254c2e12e" }, "owner_lane": "", "provenance": { diff --git a/native/.crumb b/native/.crumb index 470ae45c..075626a4 100644 --- a/native/.crumb +++ b/native/.crumb @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "1b9b958d2f033dcf14a2b22e6166a3d2f44d03d8af9ee5ab3a93751523cc845b", - "last_commit": "e4bc7aa", + "digest": "61b2904194490fb8fa5b1dba19bb861308efc31be1ad5cc909d8f226d1e45d05", + "last_commit": "b4c351e", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, @@ -115,15 +115,15 @@ "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:bb2fa8f7899f1249c331015e30b462056dab1e9dc7df60eafaa715999f613321", - "compiled_at": "2026-10-31T03:50:47Z", + "children_root": "sha256:984d253047fdba696dc25901a6d5a1035256acd1f0062acc1f7b9b8635a68cc5", + "compiled_at": "2026-10-31T03:56:20Z", "compiler": "crumb-compile/1", - "digest": "sha256:1d869fc8837e95da35cbe14cd535f5c023ab536fead815845eb8d2c4784bcb4a", + "digest": "sha256:0660522029d1706b495ea85da3194a9bcad5d7938241850f23920cd513f1b46d", "evidence_files": 24, "evidence_root": "sha256:ecc7ccf2e924c221a5bac1d91e23b13d8f3c8d78c2a893a882ed7ca5e88d855d", "files": 770, - "generated_at_commit": "b9580267ad8852e8f81391addf20fdd244b91a00", - "source_tree": "sha256:eb1fc62f665224ab3fcdcaa8e25ad1ae711503507d3fa500b8e64527dbf84ee9" + "generated_at_commit": "b4c351e7bc9c01e9384c19e9d6fc2ab4d2472e85", + "source_tree": "sha256:5c4657f8d59935d52f7097f40cad08394b97854d7c91f7fe6bd9012a0576cedd" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 1c1f2b19..ee8038b4 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -81,8 +81,8 @@ "purpose": "Directory native/kernel/mm. Purpose not yet described by a human." }, { - "digest": "ef3844c1228b5fc5b740f944b4a3d2539fc4a816bf5402fa47fce6b50850d543", - "last_commit": "792181f", + "digest": "b8e137e0cb61e080d217fe51961287a0803aa7a3f53424c67dbb1d153d32085d", + "last_commit": "b4c351e", "name": "svc", "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, @@ -99,15 +99,15 @@ "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:272980ba0ceda75ccf3e1724c6ef1ba325163cb86c34af6b021c7a2dba7dd0a3", - "compiled_at": "2026-10-31T03:50:47Z", + "children_root": "sha256:bfaaca1717891ea213270f2368dec6024439319706b4be0bc841942f5c408441", + "compiled_at": "2026-10-31T03:56:20Z", "compiler": "crumb-compile/1", - "digest": "sha256:1b9b958d2f033dcf14a2b22e6166a3d2f44d03d8af9ee5ab3a93751523cc845b", + "digest": "sha256:61b2904194490fb8fa5b1dba19bb861308efc31be1ad5cc909d8f226d1e45d05", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 515, - "generated_at_commit": "b9580267ad8852e8f81391addf20fdd244b91a00", - "source_tree": "sha256:d43e0abbd73a52f5c53ae318bb488b978439cc2eb9f75254723b838cdec00e93" + "generated_at_commit": "b4c351e7bc9c01e9384c19e9d6fc2ab4d2472e85", + "source_tree": "sha256:98198dfdfcf95267c4f2dd7c63f6f520d3a0281546c1f83519a359408bdc1fc6" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/README.md b/native/kernel/README.md index 68c92d9b..18584762 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -275,6 +275,34 @@ night line, the drawing cores, the codec mapped through the command rings, the chirp stream running and its stop. `AIENOS_IMAC_KERNEL_KEEP_DIR=` keeps each run's serial log and a `.wav` recording of its sound. +**Microphone (first cut, 2026-10-18).** On the same controller the first input stream records +1 s from the microphone right after the chirp starts, then `ck_x86_hda_step` stops it and prints +what arrived: `sound: microphone recorded 1000 ms: N samples, P% nonzero (first at i), peak, +rms, dc`. Behind a CS8409 on an Apple board the built-in microphone is a digital microphone +wired into the bridge (iMac boards: pin 0x45 to converter 0x23, DMIC2; MacBook Pro boards: 0x44 +to 0x22, DMIC1; source: davidjo/snd_hda_macbookpro `patch_cirrus_real84.h`, which replays what +macOS sends): coefficient 0x09 selects it, 0x82 turns on its clock, the pin gets In Enable +(HDA 7.3.3.13) and the converter the stream tag, 44.1 kHz 24-bit. Any other codec gets its +first analogue input converter fed by a microphone or line-in pin. The QEMU kernel test uses +`hda-duplex` (line-in pin 0x05 to converter 0x04) and requires the path, the stream running +and the summary; QEMU feeds silence, so 0% nonzero there is expected. On the iMac the summary +line in the lab report is the receipt for whether any sound comes through; the mainline Linux +driver never got this microphone working, so a silent first run is a real possibility and the +next step is then the bridge's coefficient dump against the macOS replay. + +**Device inventory.** The PCI walk prints one `pci: fn bus:dev.fn id=vendor:device class=...` line +for every function it finds, before the drivers claim theirs. On the real machine these lines are +the ground truth for which drivers are still missing (lab report allowlist: `pci:`). + +**Sleep.** "goodbye", or a tap of the power button, puts Allen to sleep: the screen goes +black but for a faint point of light where he was, nothing moves, nothing is typed. Any key or +another tap wakes him and the sky comes back at once (the waking key is not typed). Holding the +power button 4 s is still the chipset's own hard power-off. The button is read by polling the +PM1 status register named in the ACPI FADT (bit 8, PWRBTN_STS; its interrupt enable is cleared so +the firmware never sees the press); the QEMU keyboard test drives it with the monitor's +`system_powerdown`. Without a keyboard there is no window and no sleep: the screen holds +CK_X86_HOLD_S seconds, then ACPI S5. + **Keyboard and Allen's window.** `x86/xhci_x86.c` drives a wired USB boot keyboard (polled xHCI, through USB 2.0 hubs). When one is ready, Allen wakes: the person is his guest. A quiet glass bar comes up at the bottom for what @@ -291,7 +319,12 @@ talk, your name for the session, facts about the machine, how long it has been awake and sums said in words ("what is 12 times 4"); anything else gives "I don't know that yet." Answers print as `allen: ` on the console. The window has no idle countdown: it stays up until "goodbye" (then ACPI S5, or a -restart in the lab image) or the power button. The conversation stays on the computer: `keyboard_line:` and `allen:` +restart in the lab image) or the power button. Unplugging the keyboard and plugging it +(or another) back in works: the driver watches the keyboard's root port, prints +`keyboard: unplugged`, releases the old device and runs discovery again, then +`keyboard: ready` once more (the QEMU test does exactly this from outside the +guest). A keyboard plugged in for the first time after start-up is not found: the +controller is halted when no keyboard was there at start. The conversation stays on the computer: `keyboard_line:` and `allen:` are off the lab report's allowlist, which carries only `screen: Allen answered (N characters in, M out)`. Without a keyboard or the memory the text screen and its 60 s hold stay. Tests: `scripts/ck_allen_ui_test.sh` (host) and diff --git a/native/kernel/svc/.crumb b/native/kernel/svc/.crumb index 59a43df6..3472f274 100644 --- a/native/kernel/svc/.crumb +++ b/native/kernel/svc/.crumb @@ -24,20 +24,20 @@ }, { "digest": "259013cfeff5387fa3aa04f48cd615af1932d5c2a7dfe60e6d09d90cc3c51c6a", - "last_commit": "4eb74bf", + "last_commit": "2c3d3cf", "name": "tests", "purpose": "Directory native/kernel/svc/tests. Purpose not yet described by a human." } ], "children_root": "sha256:adfe21753ab01289100e5475adaa069d48fd2826311005574e2e40b38dcade98", - "compiled_at": "2026-10-31T02:24:33Z", + "compiled_at": "2026-10-31T02:58:08Z", "compiler": "crumb-compile/1", - "digest": "sha256:ef3844c1228b5fc5b740f944b4a3d2539fc4a816bf5402fa47fce6b50850d543", + "digest": "sha256:b8e137e0cb61e080d217fe51961287a0803aa7a3f53424c67dbb1d153d32085d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 55, - "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", - "source_tree": "sha256:500f9dbf12ad5645e87d96886e45f38adb8454b91f0520404f70110df1f56d44" + "generated_at_commit": "66bf338dd2c1ce4cf01f7f43094a939a33d1933a", + "source_tree": "sha256:fecd52ccc147cc31a8f8307d0a4b21cd4bb76544dadba92abc7331fb97f903ed" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/svc/allen_reply.c b/native/kernel/svc/allen_reply.c index b3ca8280..118388bc 100644 --- a/native/kernel/svc/allen_reply.c +++ b/native/kernel/svc/allen_reply.c @@ -802,7 +802,7 @@ const char *ck_allen_answer(ck_allen_mind *m, const char *line, uint64_t awake_s "what can i ask", "commands", 0}; if (any(f, help)) return "I learn what you teach me (remember my car is red) and keep notes (save the gate code is 4471), " - "then hand them back when you ask. Type goodbye to end."; + "then hand them back when you ask. Goodbye puts me to sleep."; static const char *const your_name[] = {"what is your name", "whats your name", "what s your name", "your name", 0}; if (any(f, your_name)) @@ -906,7 +906,7 @@ const char *ck_allen_answer(ck_allen_mind *m, const char *line, uint64_t awake_s return m->out; } if (find(f, "good night")) - return "Good night. Type goodbye when you want this computer to turn off."; + return "Good night. Type goodbye and I sleep; hold the power button 4 seconds to turn this computer off."; static const char *const test[] = {"test", "testing", "can you hear me", "are you there", 0}; if (any(f, test)) return "I hear you. Everything is working."; diff --git a/native/kernel/ui/allen_ui.c b/native/kernel/ui/allen_ui.c index ca105132..c90f88ec 100644 --- a/native/kernel/ui/allen_ui.c +++ b/native/kernel/ui/allen_ui.c @@ -51,6 +51,8 @@ static struct { volatile char lock; volatile int refresh; unsigned input_gen, said_gen, map_gen, wake_gen; + int sleep; + unsigned sleep_gen; char input[TEXT_MAX]; unsigned input_len; char line[TEXT_MAX], reply[TEXT_MAX]; @@ -84,6 +86,8 @@ static struct { unsigned input_len; uint32_t key_t; unsigned seen_input, seen_said, seen_map, seen_wake; + int asleep; /* dark screen, nothing drawn but the mark */ + unsigned seen_sleep; int input_moved; /* the conversation */ struct words now, next; /* now: on screen; next: what Allen will say */ @@ -498,9 +502,24 @@ static void present(const ck_rect *r) } } +/* Asleep: black, and a faint point of light where Allen was, so a dark room + * still shows the computer is on. */ +static void dark(const ck_rect *r) +{ + for (int32_t y = r->y; y < r->y + r->h; y++) + for (int32_t x = 0; x < r->w; x++) + ui.back[(size_t)y * (size_t)ui.w + r->x + x] = 0; + ck_glow(&ui.cv, r, ui.cx * 16 + 8, ui.cy * 16 + 8, S(6) * 16, CK_RGB(120, 130, 160), 40); /* radius in 1/16 px */ + present(r); +} + static void compose(const ck_rect *r) { uint32_t t = ui.t; + if (ui.asleep) { + dark(r); + return; + } ck_night_base(&ui.night, &ui.cv, r); ck_night_lights(&ui.night, &ui.cv, r, ui.shimmer, ui.level * ui.shimmer >> 9); int32_t rad; @@ -620,6 +639,11 @@ static void take_notes(uint32_t t) if (!ui.on) ui.on = 1, ui.wake_t = t, ui.quiet_t = ck_max((int32_t)t, (int32_t)FORMED_MS); } + if (note.sleep_gen != ui.seen_sleep) { + ui.seen_sleep = note.sleep_gen; + ui.asleep = note.sleep; + mark_all(); /* the whole screen changes either way */ + } if (note.input_gen != ui.seen_input) { ui.seen_input = note.input_gen; if (note.input_len > ui.input_len) @@ -675,6 +699,8 @@ static void advance(uint32_t t) { uint32_t prev = ui.last, dt = t - prev; take_notes(t); + if (ui.asleep) + return; /* nothing moves while Allen sleeps; the tiles marked on the way in are drawn once */ /* the sky */ ck_night_at(&ui.night, t); if (t < CK_NIGHT_FADE_END_MS + FRAME_MS * 2) @@ -891,6 +917,16 @@ void ck_allen_ui_refresh(void) unlock(); } +void ck_allen_ui_sleep(int asleep, uint64_t now) +{ + (void)now; + lock(); + note.sleep = asleep != 0; + note.sleep_gen++; + unlock(); +} +int ck_allen_ui_asleep(void) { return ui.asleep; } + void ck_allen_ui_wake(const char *footer, uint64_t now) { (void)now; diff --git a/native/kernel/ui/allen_ui.h b/native/kernel/ui/allen_ui.h index 685f9b78..9080ec5f 100644 --- a/native/kernel/ui/allen_ui.h +++ b/native/kernel/ui/allen_ui.h @@ -51,6 +51,10 @@ int ck_allen_ui_help(void); /* The whole screen is drawn again by the next frame, at once (after * something else wrote to it). */ void ck_allen_ui_refresh(void); +/* Allen sleeps (asleep = 1): the screen goes dark but for a faint mark where he + * was, nothing moves; asleep = 0 brings the sky back, at once. */ +void ck_allen_ui_sleep(int asleep, uint64_t now); +int ck_allen_ui_asleep(void); /* Frames drawn, the slowest and the average (microseconds). */ void ck_allen_ui_stats(uint32_t *frames, uint32_t *slowest_us, uint32_t *average_us); diff --git a/native/kernel/ui/tests/allen_ui_test.c b/native/kernel/ui/tests/allen_ui_test.c index 4a909228..649a4c1c 100644 --- a/native/kernel/ui/tests/allen_ui_test.c +++ b/native/kernel/ui/tests/allen_ui_test.c @@ -495,6 +495,25 @@ int main(int argc, char **argv) run_to(m0 + 15000); CHECK(added(&P, sky, mx, my, mw, mh) < 400, "map: it goes again after a while"); } + /* ---- sleep: dark but for a faint mark, nothing moves; waking brings the sky back ---- */ + { + ck_allen_ui_sleep(1, now_us); + uint32_t s0 = (uint32_t)(now_us / 1000); + run_to(s0 + 200); + CHECK(ck_allen_ui_asleep(), "sleep: asleep after ck_allen_ui_sleep(1)"); + unsigned lit = 0; + for (uint32_t y = 0; y < H; y += 4) + for (uint32_t x = 0; x < W; x += 4) + lit += (fb[(size_t)y * W + x] & 0xffffffu) != 0; + CHECK(lit > 3 && lit < 4000, "sleep: the screen is dark but for a faint mark (more than one pixel)"); + memcpy(copy, fb, (size_t)W * H * 4); + run_to(s0 + 2000); + CHECK(differ(fb, copy, W, W, H, 0) == 0, "sleep: nothing moves while asleep"); + ck_allen_ui_sleep(0, now_us); + run_to(s0 + 2300); + CHECK(!ck_allen_ui_asleep(), "sleep: awake after ck_allen_ui_sleep(0)"); + CHECK(differ(fb, copy, W, W, H, 0) > 100000, "sleep: the sky is back after waking"); + } uint32_t frames, slowest, average; ck_allen_ui_stats(&frames, &slowest, &average); printf("note: %u frames at 3840x2160 on one core of this host: average %u us, slowest %u us\n", frames, average, diff --git a/native/kernel/x86/hda_x86.c b/native/kernel/x86/hda_x86.c index 4e46194f..8b18d2f6 100644 --- a/native/kernel/x86/hda_x86.c +++ b/native/kernel/x86/hda_x86.c @@ -26,7 +26,22 @@ * silence after it. A stream loops by design (the controller * has no play-once), so ck_x86_hda_step stops it once the chirp is over. * Register offsets and bits: Linux's hda_register.h and hda_verbs.h; the - * Intel PCI settings are in pci_x86.c (docs-read records). */ + * Intel PCI settings are in pci_x86.c (docs-read records). + * + * The microphone: on the same controller the first input stream records + * CAP_MS of sound into memory. Behind a CS8409 on an Apple board the built-in + * microphone is a digital microphone wired straight into the bridge (pin 0x45 + * to converter 0x23 on iMac boards, DMIC2; 0x44 to 0x22 on MacBook Pro + * boards, DMIC1: davidjo/snd_hda_macbookpro real84.h cs_8409_capture_real, + * which replays macOS); the bridge's coefficient 0x09 selects the microphone + * (DMICx_MO=10b, SR=1) and 0x82 turns on its clock (DMICx_SCL_EN), then the + * pin's input path is enabled (HDA 7.3.3.13 In Enable) and the converter is + * given the stream's tag. Any other codec gets its first analogue input + * converter with a path from a line-in or microphone pin. Once the time is + * up ck_x86_hda_step stops the stream and reports what arrived (samples, + * nonzero share, peak, rms, dc) so the first real run says whether sound + * comes through at all. 24-bit samples sit left-justified in 32-bit + * containers (HDA 4.5.1). */ #include "../core/ck_internal.h" #include "../mm/frames.h" #include "../ui/chirp.h" @@ -99,6 +114,7 @@ #define P_GPIO 0x11 #define P_AMP_OUT 0x12 #define W_AUD_OUT 0 +#define W_AUD_IN 1 #define W_MIX 2 #define W_SEL 3 #define W_PIN 4 @@ -110,9 +126,12 @@ #define WC_POWER (1u << 10) #define PC_HP_DRV (1u << 3) #define PC_OUT (1u << 4) +#define PC_IN (1u << 5) #define PC_EAPD (1u << 16) #define FMT_48K_16_STEREO 0x0011u #define TAG 1u /* the stream's tag; the converters listen for it */ +#define CAP_TAG 2u /* the microphone stream's tag */ +#define CAP_MS 1000u /* how long the microphone is recorded */ #define CHUNK 65536u /* bytes per buffer descriptor */ #define HDA_TAIL_MS 8000u /* silence after the chirp, so a late stop never replays it */ #define MAX_NID 128u @@ -130,6 +149,12 @@ static unsigned g_fmt; /* the stream format: FMT_48K_16_STEREO unless a codec ta static volatile uint8_t *play_bar; static unsigned play_sd; static uint64_t play_t0; +/* the microphone stream */ +static volatile uint8_t *cap_bar; +static unsigned cap_sd, cap_a, cap_adc, cap_pin, cap_fmt; +static uint8_t *cap_buf; +static size_t cap_bytes; +static uint64_t cap_t0; static uint8_t r8(unsigned o) { return g_bar[o]; } static uint16_t r16(unsigned o) { return *(volatile uint16_t *)(g_bar + o); } @@ -482,7 +507,35 @@ static void cs_amp_on(unsigned chip, unsigned slot) i2c_write(chip, regs[k][0], regs[k][0] == 0x03 ? 0x80u | slot : regs[k][0] == 0x04 ? CS_AMP_VOLUME : regs[k][1]); } -static unsigned cs8409_apple(unsigned a, unsigned afg, char *say, size_t say_n) +/* The built-in digital microphone behind the bridge (real84.h cs_8409_capture_real, + * intmike_format_setup_enable, intmike_volume_setup, intmike_stream_on_nid). */ +static void cs_mic_open(unsigned a, uint32_t sub) +{ + unsigned pin = 0x45, adc = 0x23, dmic = 2, mo = 0x0080, scl = 0x0002; /* iMac boards */ + if (sub != 0x106b1000 && sub != 0x106b0f00 && sub != 0x106b0e00) { + pin = 0x44; adc = 0x22; dmic = 1; mo = 0x0020; scl = 0x0001; /* MacBook Pro boards */ + } + if (W[pin].type != W_PIN || W[adc].type != W_AUD_IN) { + ck_printf("sound: codec=%u CS8409 microphone: no pin 0x%02x / converter 0x%02x pair; not recorded\n", a, pin, adc); + return; + } + verb(a, adc, V_POWER, 0, 0); + verb(a, adc, V_FORMAT, FMT_441_24_STEREO, 0); + unsigned c9 = coef_get(0x09), c82 = coef_get(0x82); + coef_set(0x09, c9 | mo | 0x0003u); /* DMICx_MO=10b, DMIC1/2_SR=1 */ + verb(a, adc, V_CONNECT_SEL, 0, 0); + verb(a, adc, V_AMP, 0x7000u | 0x27u, 0); /* input, both channels, unmuted, macOS's gain step */ + coef_set(0x82, c82 | scl); /* DMICx_SCL_EN: the microphone's clock */ + verb(a, pin, V_PIN_CTL, 0x20, 0); /* In Enable */ + verb(a, adc, V_STREAM, CAP_TAG << 4, 0); + cap_a = a; + cap_adc = adc; + cap_pin = pin; + cap_fmt = FMT_441_24_STEREO; + ck_printf("sound: codec=%u CS8409 microphone: pin 0x%02x -> converter 0x%02x (DMIC%u), coef 0x09 0x%04x->0x%04x, " + "0x82 0x%04x->0x%04x, gain step 0x27\n", a, pin, adc, dmic, c9, coef_get(0x09), c82, coef_get(0x82)); +} +static unsigned cs8409_apple(unsigned a, unsigned afg, uint32_t sub, char *say, size_t say_n) { static const uint8_t amps[4] = {0xd8, 0xda, 0xdc, 0xde}; static const uint8_t amp_reset[][2] = {{0x01, 0xfc}, {0x02, 0x04}, {0x03, 0x80}, {0x04, 0xcf}, {0x06, 0x51}, @@ -563,6 +616,7 @@ static unsigned cs8409_apple(unsigned a, unsigned afg, char *say, size_t say_n) verb(a, 0x02, V_STREAM, TAG << 4, 0); verb(a, 0x03, V_STREAM, TAG << 4, 0); g_fmt = FMT_441_24_STEREO; + cs_mic_open(a, sub); ck_printf("sound: codec=%u CS8409 bridge set up: 4 amplifiers at 0x%02x volume, %u I2C transfer(s) unconfirmed%s, " "coef 0x01=0x%04x 0x17=0x%04x 0x82=0x%04x; %u ms\n", a, CS_AMP_VOLUME, cs_i2c_bad, cs_i2c_bad > 12 ? " (gave up)" : "", coef_get(0x01), coef_get(0x17), coef_get(0x82), @@ -626,7 +680,7 @@ static unsigned codec_open(unsigned ctrl, unsigned a, char *say, size_t say_n) verb(a, cs4208_words[k][0], cs4208_words[k][1], cs4208_words[k][2], 0); if (id == 0x10138409 && (sub >> 16) == 0x106b && W[0x24].type == W_PIN && W[0x25].type == W_PIN && W[0x02].type == W_AUD_OUT && W[0x03].type == W_AUD_OUT) - return cs8409_apple(a, afg, say, say_n); + return cs8409_apple(a, afg, sub, say, say_n); /* output pins, speakers first: device 1 speaker, 0 line out, 2 headphone */ static const unsigned order[3] = {1, 0, 2}; unsigned opened = 0; @@ -648,6 +702,33 @@ static unsigned codec_open(unsigned ctrl, unsigned a, char *say, size_t say_n) for (unsigned i = 1; i < plen && m < (int)say_n - 6; i++) m += ck_snprintf(say + m, say_n - (size_t)m, i > 1 ? ",0x%02x" : "0x%02x", path[i]); } + /* the first analogue input converter fed by a microphone or line-in pin */ + for (unsigned nid = first; nid < first + n && nid < MAX_NID && !cap_adc; nid++) { + const struct wid *x = &W[nid]; + if (x->type != W_AUD_IN || (x->caps & WC_DIGITAL)) + continue; + for (unsigned k = 0; k < x->nconn; k++) { + const struct wid *p = &W[x->conn[k]]; + unsigned dev = p->cfg >> 20 & 15u; + if (p->type != W_PIN || !(p->pincap & PC_IN) || (p->cfg >> 30) == 1 || (dev != 0xa && dev != 8)) + continue; + verb(a, nid, V_POWER, 0, 0); + verb(a, x->conn[k], V_POWER, 0, 0); + verb(a, x->conn[k], V_PIN_CTL, 0x20, 0); /* In Enable */ + verb(a, nid, V_CONNECT_SEL, k, 0); + if (x->caps & WC_IN_AMP) + verb(a, nid, V_AMP, 0x7000u | zero_db(x->caps & WC_AMP_OVRD ? x->amp_in : afg_in), 0); + verb(a, nid, V_FORMAT, g_fmt, 0); + verb(a, nid, V_STREAM, CAP_TAG << 4, 0); + cap_a = a; + cap_adc = nid; + cap_pin = x->conn[k]; + cap_fmt = g_fmt; + ck_printf("sound: codec=%u microphone: pin 0x%02x (%s) -> converter 0x%02x\n", a, cap_pin, + dev == 0xa ? "mic" : "line in", nid); + break; + } + } if (opened && (sub >> 16) == 0x106b && gpio) { /* Apple: the GPIOs switch the amplifiers on */ unsigned all = gpio >= 8 ? 0xffu : (1u << gpio) - 1u; verb(a, afg, V_GPIO_MASK, all, 0); @@ -736,6 +817,104 @@ static int stream_play(unsigned ctrl, unsigned sd, uint8_t *buf, size_t bytes, u return 0; } +/* CAP_MS of the microphone into buf through input stream sd (one buffer, the + * stream loops over it; ck_x86_hda_step stops it and reads it). */ +static int stream_capture(unsigned ctrl, unsigned sd, uint8_t *buf, size_t bytes, uint64_t *bdl) +{ + unsigned s = SD0 + 0x20 * sd; + w8(s, 0); + wait8(s, RUN, 0, 10); + w8(s, SRST); + if (wait8(s, SRST, SRST, 10)) { + ck_printf("sound: ctrl=%u input stream did not enter reset\n", ctrl); + return -1; + } + w8(s, 0); + if (wait8(s, SRST, 0, 10)) { + ck_printf("sound: ctrl=%u input stream did not leave reset\n", ctrl); + return -1; + } + const unsigned rate = cap_fmt == FMT_441_24_STEREO ? 44100u : 48000u, fb = cap_fmt == FMT_441_24_STEREO ? 8u : 4u; + size_t used = (size_t)rate * CAP_MS / 1000u * fb & ~(size_t)127; + if (used > bytes) + used = bytes & ~(size_t)127; + memset(buf, 0, used); + flush(buf, used); + unsigned entries = (unsigned)((used + CHUNK - 1) / CHUNK); + for (unsigned k = 0; k < entries; k++) { + size_t off = (size_t)k * CHUNK, len = used - off < CHUNK ? used - off : CHUNK; + bdl[2 * k] = (uint64_t)(uintptr_t)(buf + off); + bdl[2 * k + 1] = (uint64_t)len; + } + flush(bdl, (size_t)entries * 16); + w32(s + SD_CBL, (uint32_t)used); + w16(s + SD_LVI, (uint16_t)(entries - 1)); + w16(s + SD_FMT, (uint16_t)cap_fmt); + w32(s + SD_BDLPL, (uint32_t)(uintptr_t)bdl); + w32(s + SD_BDLPU, (uint32_t)((uint64_t)(uintptr_t)bdl >> 32)); + w8(s + 2, (uint8_t)((r8(s + 2) & 0x0fu) | CAP_TAG << 4)); + w8(s + SD_STS, 0x1c); + cap_t0 = ck_rdtsc(); + w8(s, RUN); + spin_us(2000); + ck_printf("sound: ctrl=%u stream %u recording %u ms from the microphone (pin 0x%02x -> converter 0x%02x, format " + "0x%04x, %u bytes); position after 2 ms %u bytes, status 0x%02x\n", ctrl, sd, CAP_MS, cap_pin, cap_adc, + cap_fmt, (unsigned)used, r32(s + SD_LPIB), r8(s + SD_STS)); + cap_bar = g_bar; + cap_sd = s; + cap_buf = buf; + cap_bytes = used; + return 0; +} +static uint32_t isqrt64(uint64_t v) +{ + uint64_t r = 0, bit = 1ull << 62; + while (bit > v) + bit >>= 2; + while (bit) { + if (v >= r + bit) { + v -= r + bit; + r = (r >> 1) + bit; + } else + r >>= 1; + bit >>= 2; + } + return (uint32_t)r; +} +/* The recording stopped and summed up: how much of it is sound at all. */ +static void capture_done(void) +{ + volatile uint8_t *b = cap_bar; + cap_bar = 0; + uint32_t pos = *(volatile uint32_t *)(b + cap_sd + SD_LPIB); + uint8_t sts = b[cap_sd + SD_STS]; + b[cap_sd] = 0; + verb(cap_a, cap_adc, V_STREAM, 0, 0); + verb(cap_a, cap_pin, V_PIN_CTL, 0, 0); + flush(cap_buf, cap_bytes); + const int wide = cap_fmt == FMT_441_24_STEREO; + size_t n = cap_bytes / (wide ? 4u : 2u), nz = 0, first = n; + int32_t peak = 0; + int64_t sum = 0; + uint64_t sq = 0; + for (size_t i = 0; i < n; i++) { + int32_t v = wide ? ((const int32_t *)cap_buf)[i] >> 16 : ((const int16_t *)cap_buf)[i]; + if (v) { + nz++; + if (first == n) + first = i; + } + int32_t m = v < 0 ? -v : v; + if (m > peak) + peak = m; + sum += v; + sq += (uint64_t)((int64_t)v * v); + } + ck_printf("sound: microphone recorded %u ms: %u samples, %u%% nonzero (first at %u), peak %d, rms %u, dc %d (16-bit " + "scale), position %u bytes, status 0x%02x\n", CAP_MS, (unsigned)n, (unsigned)(n ? nz * 100 / n : 0), + (unsigned)first, peak, n ? isqrt64(sq / n) : 0u, (int)(n ? sum / (int64_t)n : 0), pos, sts); +} + int ck_x86_hda_start(unsigned ctrl, volatile uint8_t *bar, struct ck_frames *fr, uint64_t tsc_hz, uint64_t night_t0, int play) { @@ -743,6 +922,7 @@ int ck_x86_hda_start(unsigned ctrl, volatile uint8_t *bar, struct ck_frames *fr, g_hz = tsc_hz; g_fmt = FMT_48K_16_STEREO; rings = 0; + cap_adc = 0; uint16_t gcap = r16(GCAP); unsigned iss = gcap >> 8 & 15u, oss = gcap >> 12 & 15u, bss = gcap >> 3 & 31u, nsd = iss + oss + bss; unsigned running = 0, corb_on = r8(CORBCTL) & RUN, rirb_on = r8(RIRBCTL) & RUN; @@ -805,6 +985,16 @@ int ck_x86_hda_start(unsigned ctrl, volatile uint8_t *bar, struct ck_frames *fr, ck_printf("sound: ctrl=%u opened %u output pin(s): %s\n", ctrl, opened, say); if (!play) return 0; + if (cap_adc && iss) { + size_t cb = (size_t)44100u * CAP_MS / 1000u * 8u; + cb = (cb + CK_PAGE - 1) & ~(size_t)(CK_PAGE - 1); + uint64_t cpa, cbpa; + if (!fr || ck_frames_alloc(fr, cb / CK_PAGE, CK_PAGE, &cpa) || ck_frames_alloc(fr, 1, CK_PAGE, &cbpa)) + ck_printf("sound: ctrl=%u no memory for the microphone (%llu KiB)\n", ctrl, (unsigned long long)(cb >> 10)); + else + stream_capture(ctrl, 0, (uint8_t *)(uintptr_t)cpa, cb, (uint64_t *)(uintptr_t)cbpa); + } else if (cap_adc) + ck_printf("sound: ctrl=%u has no input stream; the microphone is not recorded\n", ctrl); if (!night_t0) { ck_printf("sound: ctrl=%u ready; no night running, so no chirp\n", ctrl); return 0; @@ -827,6 +1017,8 @@ int ck_x86_hda_start(unsigned ctrl, volatile uint8_t *bar, struct ck_frames *fr, void ck_x86_hda_step(void) { + if (cap_bar && (ck_rdtsc() - cap_t0) * 1000 / g_hz >= CAP_MS + 100u) + capture_done(); if (!play_bar || (ck_rdtsc() - play_t0) * 1000 / g_hz < CK_CHIRP_END_MS + 200u) return; volatile uint8_t *b = play_bar; diff --git a/native/kernel/x86/kmain_x86.c b/native/kernel/x86/kmain_x86.c index 79f301dd..bebb2551 100644 --- a/native/kernel/x86/kmain_x86.c +++ b/native/kernel/x86/kmain_x86.c @@ -35,7 +35,9 @@ * NVMe disks read-only and a look at the Ethernet chip (pci_x86.c, * ahci_x86.c), and the final report. With a keyboard, Allen's window, whose * memory lives in its own partition of the approved hard disk (memory_x86.c, - * the only disk writes). It holds the screen CK_X86_HOLD_S seconds and + * the only disk writes). Goodbye, or a tap of the power button (PM1 status, + * polled), puts Allen to sleep: a dark screen until a key or another tap. Without + * a keyboard it holds the screen CK_X86_HOLD_S seconds and * powers off through ACPI S5 (FADT PM1 control + the DSDT's \_S5 package); the lab image * (CK_X86_REPORT=1) restarts through the FADT reset register instead, back * into its network loader (native/boot/net_loader.c). @@ -287,11 +289,75 @@ static void acpi_reset(void) * (svc/allen_reply.c). Every Enter gets an answer on the console * ("allen: ..."); when a keyboard is ready and the RAM for drawing is there, * the screen switches from the boot report to Allen's window, which stays - * up (no idle countdown) until "goodbye" is typed or the power button is - * held. Without either, the text screen and its timed hold stay as they were. */ + * up (no idle countdown); "goodbye" or a tap of the power button puts Allen to + * sleep (dark screen), a key or another tap wakes him; holding the button 4 s + * is the hardware power-off. Without either, the text screen and its timed hold stay as they were. */ static int allen_on; static uint64_t allen_bye; /* TSC when Allen said goodbye; 0 = still talking */ static uint64_t allen_woke; /* TSC when Allen's window took the screen */ +static int allen_asleep; /* the screen is dark; a key or the power button wakes him */ +static uint16_t pm1_sts; /* PM1a status port (FADT), 0 = no power-button watch */ +static uint64_t pwr_last; /* TSC of the last power-button tap taken */ + +/* The power button sets PWRBTN_STS (PM1 status bit 8, write 1 to clear) whether or + * not it is enabled as an interrupt (chipset book 332691 p163). The enable bit is + * cleared so no SMI or SCI goes to the firmware while we poll; holding the button + * 4 s is still the chipset's own hard power-off. */ +static void power_button_watch(void) +{ + const uint8_t *fadt = hand && hand->rsdp ? ck_acpi_lookup(hand->rsdp, "FACP") : 0; + if (!fadt || rd32(fadt, 4) < 92) { + ck_puts("power: no FADT; the power button is not watched\n"); + return; + } + uint32_t evt = rd32(fadt, 56); /* PM1a_EVT_BLK */ + uint8_t len = fadt[88]; /* PM1_EVT_LEN: status then enable, len/2 each */ + if (!evt || evt > 0xffff || len < 4) { + ck_printf("power: PM1a event block 0x%x (%u bytes) is not a watchable I/O port\n", evt, len); + return; + } + /* Real chipsets latch PWRBTN_STS whether or not PWRBTN_EN is set (ACPI 6.5 + * 4.8.2.2.1.2: "unconditionally set"), and with it clear a press raises no SMI# + * or SCI (332691 PM1_EN). QEMU's model (hw/acpi/core.c acpi_pm1_evt_power_down) + * latches only when PWRBTN_EN is set; interrupts are off here, so under a + * hypervisor the bit is set instead and the SCI line it raises goes nowhere. */ + uint32_t r[4]; + ck_cpuid(1, 0, r); + int hv = (r[2] >> 31) & 1; + uint16_t en = (uint16_t)(evt + len / 2); + uint16_t env = (uint16_t)(ck_inw(en) & ~0x100u); + if (hv) + env |= 0x100; + ck_outw(en, env); + ck_outw((uint16_t)evt, 0x100); /* a press from before now is forgotten */ + pm1_sts = (uint16_t)evt; + ck_printf("power: button watched at PM1 status port 0x%x (tap: sleep or wake; hold 4 s: off%s)\n", evt, + hv ? "; enable bit set for the hypervisor's chipset model" : ""); +} +static int power_button_tapped(void) +{ + if (!pm1_sts || !(ck_inw(pm1_sts) & 0x100)) + return 0; + ck_outw(pm1_sts, 0x100); + uint64_t now = ck_rdtsc(); + if (now - pwr_last < tsc_hz / 2) /* bounce */ + return 0; + pwr_last = now; + return 1; +} +static void allen_sleep(int on) +{ + if (allen_asleep == on) + return; + allen_asleep = on; + ck_allen_ui_sleep(on, ck_rdtsc()); + if (on) + ck_puts("power: Allen asleep (any key or a tap of the power button wakes him)\n"); + else { + ck_x86_kbd_discard(); + ck_puts("power: Allen awake\n"); + } +} #define STEP_MAX 16 static struct { @@ -310,7 +376,14 @@ static ck_allen_facts allen_facts; /* filled at the summary line */ static ck_allen_mind allen_mind; static ck_allen_notes allen_notes; /* loaded from disk at the window, or empty */ -static void allen_edit(const char *buf, unsigned len) { ck_allen_ui_input(buf, len, ck_rdtsc()); } +static void allen_edit(const char *buf, unsigned len) +{ + if (allen_asleep) { /* the key only wakes him */ + allen_sleep(0); + return; + } + ck_allen_ui_input(buf, len, ck_rdtsc()); +} /* The notes map beside the window: the newest live notes (point 0 the newest) * and the links among them; every live note and link is counted. */ @@ -342,6 +415,10 @@ static void allen_map(void) static void allen_line(const char *text) { + if (allen_asleep) { + allen_sleep(0); + return; + } const char *reply = ck_allen_answer(&allen_mind, text, ck_rdtsc() / tsc_hz); /* What was taught goes to disk before Allen says it will remember it: a * note first, then the memory copy that counts it; goodbye saves the line @@ -525,7 +602,7 @@ static void allen_window(void) } night_mib = (uint32_t)(need >> 20); } - ck_snprintf(footer, sizeof footer, "Type goodbye to %s this computer", CK_X86_REPORT ? "restart" : "turn off"); + ck_snprintf(footer, sizeof footer, "Type goodbye and this computer sleeps; any key wakes it"); ck_printf("screen: Allen's window (%ux%u, %u MiB drawing memory)\n", w, h, night_mib); ck_x86_console_fb_off(); ck_allen_ui_refresh(); /* whatever else was on the screen goes */ @@ -533,6 +610,7 @@ static void allen_window(void) ck_x86_kbd_sink(allen_edit, allen_line); allen_on = 1; allen_woke = ck_rdtsc(); + power_button_watch(); boot_times(); night_stats("before Allen woke"); allen_map(); /* the notes loaded from disk, before the first word */ @@ -558,9 +636,15 @@ void ck_x86_hold_step(uint64_t *end) told = 1; night_stats("by 20 s after Allen woke"); } - /* No countdown while Allen's window is up; after goodbye, 4 s for the - * answer to appear, then the hold ends. */ - *end = allen_bye ? allen_bye + 4 * tsc_hz : ~0ull; + /* No countdown while Allen's window is up. After goodbye, 4 s for the answer + * to appear, then Allen sleeps; a power-button tap sleeps or wakes him. */ + if (allen_bye && ck_rdtsc() - allen_bye > 4 * tsc_hz) { + allen_bye = 0; + allen_sleep(1); + } + if (power_button_tapped()) + allen_sleep(!allen_asleep); + *end = ~0ull; } static __attribute__((noreturn)) void finish(void) @@ -578,7 +662,7 @@ static __attribute__((noreturn)) void finish(void) if (CK_X86_HOLD_S && ck_x86_kbd_ready()) { allen_window(); if (allen_on) - ck_puts("keyboard: type a line and press Enter; Allen's window stays on until you type goodbye\n"); + ck_puts("keyboard: type a line and press Enter; goodbye puts Allen to sleep, any key wakes him, holding the power button 4 s turns the computer off\n"); else ck_printf("keyboard: type a line and press Enter; the screen stays on until %u s after the last key\n", ck_x86_kbd_idle_s()); @@ -592,7 +676,7 @@ static __attribute__((noreturn)) void finish(void) /* Lab build only (make imac-kernel CK_X86_REPORT=1): sends the * allowlisted, unauthenticated report if the network is up. */ if (allen_on) - ck_puts("power: Allen's window stays on until goodbye (or the power button), then restart\n"); + ck_puts("power: Allen's window stays on; goodbye or a power-button tap puts him to sleep, hold the button 4 s to turn off\n"); else ck_printf("power: holding the screen %u s, then restart\n", (unsigned)CK_X86_HOLD_S); ck_x86_report_hold(tsc_hz, CK_X86_HOLD_S); @@ -600,7 +684,7 @@ static __attribute__((noreturn)) void finish(void) #else /* Default and resident builds: no report code is linked; nothing is sent. */ if (allen_on) - ck_puts("power: Allen's window stays on until goodbye (or the power button), then ACPI S5\n"); + ck_puts("power: Allen's window stays on; goodbye or a power-button tap puts him to sleep, hold the button 4 s to turn off\n"); else ck_printf("power: holding the screen %u s, then ACPI S5\n", (unsigned)CK_X86_HOLD_S); uint64_t end = ck_rdtsc() + (uint64_t)CK_X86_HOLD_S * tsc_hz; /* typing moves it out */ diff --git a/native/kernel/x86/pci_x86.c b/native/kernel/x86/pci_x86.c index f4377f0c..04c7a8ed 100644 --- a/native/kernel/x86/pci_x86.c +++ b/native/kernel/x86/pci_x86.c @@ -385,6 +385,8 @@ const struct ck_x86_storage_result *ck_x86_storage(uint64_t rsdp, struct ck_fram } res.pci_functions++; uint8_t ht = (uint8_t)(cr32(cfg, 0x0c) >> 16); + ck_printf("pci: fn %02x:%02x.%u id=%04x:%04x class=%06x\n", bus, dev, fn, idr & 0xffffu, idr >> 16, + cr32(cfg, 8) >> 8); /* every function, for the driver inventory */ if (nfound < PCI_MAX) found[nfound++] = (struct pfn){cfg, (uint8_t)bus, (uint8_t)dev, (uint8_t)fn, ht, (uint16_t)idr, (uint16_t)(idr >> 16), cr32(cfg, 8) >> 8}; diff --git a/native/kernel/x86/report_x86.c b/native/kernel/x86/report_x86.c index d0d2e3af..9da14424 100644 --- a/native/kernel/x86/report_x86.c +++ b/native/kernel/x86/report_x86.c @@ -192,7 +192,7 @@ size_t ck_x86_report_frame(const uint8_t mac[6], uint64_t run, const char *repor #ifndef CK_X86_REPORT_HOST /* Lab build only. Holds for `seconds` (longer while ck_x86_hold_step moves the - * end out: typing, or Allen's window until goodbye), sending the allowlisted report every + * end out: typing, or Allen's window, which stays up through sleep), sending the allowlisted report every * 2 s while the link is up. Without a working network it only waits. Returns * the rounds sent. */ unsigned ck_x86_report_hold(uint64_t tsc_hz, unsigned seconds) diff --git a/native/kernel/x86/x86.h b/native/kernel/x86/x86.h index 21a6aede..293f40ab 100644 --- a/native/kernel/x86/x86.h +++ b/native/kernel/x86/x86.h @@ -198,6 +198,7 @@ void ck_x86_kbd_done(void); * that changed the line, line(text) after each Enter (after its * "keyboard_line:" line). Either may be NULL. */ void ck_x86_kbd_sink(void (*edit)(const char *buf, unsigned len), void (*line)(const char *text)); +void ck_x86_kbd_discard(void); /* drop the line being typed (the key that woke Allen) */ /* kmain_x86.c: one step of the screen hold: waiting keys (which may move *end * out) and the window's animation. Called in every hold loop. */ void ck_x86_hold_step(uint64_t *end); diff --git a/native/kernel/x86/xhci_x86.c b/native/kernel/x86/xhci_x86.c index ae51d571..fc19dd0a 100644 --- a/native/kernel/x86/xhci_x86.c +++ b/native/kernel/x86/xhci_x86.c @@ -68,6 +68,7 @@ enum { P_DCBAA = 0, P_CMD, P_EVT, P_ERST, P_INCTX, P_BUF, P_INTR, P_SPARRAY, P_D #define PS_PR 0x10u #define PS_PP 0x200u #define PS_PRC 0x200000u +#define PS_CSC 0x20000u /* connect status change, RW1C */ #define PS_CHANGES 0x00fe0000u #define PS_KEEP (PS_PP | 0x0e000000u) /* PP and the wake enables: RW, not RW1C */ #define T_NORMAL 1u @@ -78,9 +79,11 @@ enum { P_DCBAA = 0, P_CMD, P_EVT, P_ERST, P_INCTX, P_BUF, P_INTR, P_SPARRAY, P_D #define T_ENABLE_SLOT 9u #define T_ADDRESS 11u #define T_CONFIGURE 12u +#define T_DISABLE_SLOT 10u #define T_EVALUATE 13u #define T_EV_TRANSFER 32u #define T_EV_COMMAND 33u +#define T_EV_PORT 34u /* Port Status Change Event, xHCI 6.4.2.3 */ #define TRB_TYPE(t) ((uint32_t)(t) << 10) #define TRB_IOC 0x20u #define TRB_ISP 0x4u @@ -126,6 +129,10 @@ static struct { ck_boot_kbd kd; uint8_t dci; int stopped; + int rescan; /* the keyboard's root port changed: look again */ + unsigned errors; /* failed reports or rediscoveries since the last good report or real (un)plug */ + int gave_up; /* KBD_ERR_MAX passed: waits for a real connect change */ + uint8_t kbd_port; /* root port the keyboard (or its hub) sits on */ const char *why; uint32_t last_code; } x; @@ -556,6 +563,39 @@ static int reset_root_port(uint8_t p, uint8_t *speed) return 0; } +/* Every connected root port in turn: reset it and enumerate what is behind it, + * until a boot keyboard answers. Used at start and again after a replug. */ +static void kbd_ready(void); +static int scan_ports(void) +{ + for (unsigned p = 1; p <= x.max_ports && p <= 255u && x.ndev < DEV_MAX; p++) { + if (!(rd(x.op + OP_PORTSC(p)) & PS_CCS)) + continue; + struct usbdev *d = &x.dev[x.ndev]; + zero(d, sizeof *d); + d->page = P_DEV0 + 2u * x.ndev++; + d->root_port = (uint8_t)p; + ck_snprintf(d->path, sizeof d->path, "%u", p); + if (reset_root_port((uint8_t)p, &d->speed) == 0 && enumerate(d) == 0) { + x.kbd_port = (uint8_t)p; + return 0; + } + ck_printf("usb: port %s: %s (completion %u)\n", d->path, x.why, x.last_code); + } + return fail("no boot keyboard on any port"); +} + +/* xHCI 4.6.4: Disable Slot for every device we addressed, so a fresh scan can + * enable slots again. Failures are ignored: the device is gone anyway. */ +static void forget_devices(void) +{ + for (unsigned i = 0; i < x.ndev; i++) + if (x.dev[i].slot) + (void)command(0, 0, TRB_TYPE(T_DISABLE_SLOT) | ((uint32_t)x.dev[i].slot << 24), 0, "Disable Slot"); + x.ndev = 0; + x.dci = 0; +} + static void halt(void) { wr(x.op + OP_USBCMD, rd(x.op + OP_USBCMD) & ~CMD_RS); @@ -661,19 +701,7 @@ static int start(void) any_ |= rd(x.op + OP_PORTSC(p_)) & PS_CCS; any_; })); - for (unsigned p = 1; p <= x.max_ports && p <= 255u && x.ndev < DEV_MAX; p++) { - if (!(rd(x.op + OP_PORTSC(p)) & PS_CCS)) - continue; - struct usbdev *d = &x.dev[x.ndev]; - zero(d, sizeof *d); - d->page = P_DEV0 + 2u * x.ndev++; - d->root_port = (uint8_t)p; - ck_snprintf(d->path, sizeof d->path, "%u", p); - if (reset_root_port((uint8_t)p, &d->speed) == 0 && enumerate(d) == 0) - return 0; - ck_printf("usb: port %s: %s (completion %u)\n", d->path, x.why, x.last_code); - } - return fail("no boot keyboard on any port"); + return scan_ports(); } int ck_x86_xhci_start(unsigned ctrl, volatile uint8_t *bar0, struct ck_frames *fr, uint64_t tsc_hz) @@ -710,11 +738,8 @@ int ck_x86_xhci_start(unsigned ctrl, volatile uint8_t *bar0, struct ck_frames *f x.why = ""; if (start() == 0) { g_cap = ck_rdtsc() + (uint64_t)CK_X86_KBD_MAX_S * hz; - ck_hid_decoder z = {{0}}; - g_dec = z; ck_line_reset(&g_line); - ck_printf("keyboard: ready (controller %u, port %s, %s speed, slot %u, endpoint 0x%02x)\n", ctrl, - x.kbd->path, speed_name(x.kbd->speed), x.kbd->slot, x.kd.endpoint); + kbd_ready(); return 0; } ck_printf("xhci: ctrl=%u no keyboard (%s, completion %u)\n", ctrl, x.why, x.last_code); @@ -735,6 +760,16 @@ void ck_x86_kbd_sink(void (*edit)(const char *buf, unsigned len), void (*line)(c sink_line = line; } +/* The key that woke Allen is not typed: whatever is on the line goes. */ +void ck_x86_kbd_discard(void) +{ + if (g_line.len || g_line.typed) + ck_puts("\n"); + ck_line_reset(&g_line); + if (sink_edit) + sink_edit(g_line.buf, 0); +} + static void echo(char c) { if (c == '\b') @@ -743,20 +778,42 @@ static void echo(char c) ck_printf("%c", c); } +/* The keyboard found (at start or after a replug): fresh decoder, one line for the log. */ +static void kbd_ready(void) +{ + ck_hid_decoder z = {{0}}; + g_dec = z; + x.stopped = 0; + ck_printf("keyboard: ready (controller %u, port %s, %s speed, slot %u, endpoint 0x%02x)\n", x.ctrl, x.kbd->path, + speed_name(x.kbd->speed), x.kbd->slot, x.kd.endpoint); +} + /* Handles every key report that is waiting; 1 when at least one arrived. */ static int poll_keys(void) { int got = 0; uint32_t ev[4]; while (ev_next(ev)) { - if (ev_type(ev) != T_EV_TRANSFER || (ev[3] >> 24) != x.kbd->slot || ((ev[3] >> 16) & 0x1fu) != x.dci) + if (ev_type(ev) == T_EV_PORT) { + unsigned p = ev[0] >> 24; + /* the keyboard's own root port changed: it left, or came back; while it is gone, + * a connect change on any port may be it in another socket */ + if (p == x.kbd_port || (x.stopped && p >= 1 && p <= x.max_ports && (rd(x.op + OP_PORTSC(p)) & PS_CSC))) + x.rescan = 1; + continue; + } + if (x.stopped || ev_type(ev) != T_EV_TRANSFER || (ev[3] >> 24) != x.kbd->slot || + ((ev[3] >> 16) & 0x1fu) != x.dci) continue; uint32_t cc = ev_code(ev); if (cc != CC_SUCCESS && cc != CC_SHORT) { x.stopped = 1; - ck_printf("\nkeyboard: stopped (completion %u; unplugged?)\n", cc); + x.rescan = 1; + x.errors++; + ck_printf("\nkeyboard: unplugged (completion %u); plug it back in\n", cc); return got; } + x.errors = 0; uint8_t rep[CK_HID_REPORT_LEN]; uint32_t n = CK_HID_REPORT_LEN - (ev[2] & 0xffffffu); const volatile uint8_t *b = page(P_BUF) + BUF_REPORT; @@ -794,9 +851,83 @@ static int poll_keys(void) return got; } +/* After a port change on the keyboard's root port: if the port is empty, say so once + * and wait; once something is connected again, release the old slots and run the + * start-up discovery again on every occupied root port, so a keyboard moved to + * another socket is found too. A failed discovery, or a failed report from a + * keyboard that stays plugged in, is retried up to KBD_ERR_MAX times; after that + * only a real connect change (unplug, plug back in) starts discovery again, so a + * faulty keyboard cannot keep every port in reset. */ +#define KBD_ERR_MAX 3u +/* 1 when any root port reports a connect status change (left set until kbd_rescan clears it). */ +static int any_connect_change(void) +{ + for (unsigned p = 1; p <= x.max_ports && p <= 255u; p++) + if (rd(x.op + OP_PORTSC(p)) & PS_CSC) + return 1; + return 0; +} +static void kbd_rescan(void) +{ + x.rescan = 0; + uint32_t s = rd(x.op + OP_PORTSC(x.kbd_port)); + if (!x.stopped) { + if ((s & PS_CCS) && !(s & PS_CSC)) + return; /* still connected, no connect change: nothing to do */ + x.stopped = 1; + ck_printf("\nkeyboard: unplugged; plug it back in\n"); + } + int any = 0; + for (unsigned p = 1; p <= x.max_ports && p <= 255u; p++) { + uint32_t off = x.op + OP_PORTSC(p), ps = rd(off); + if (ps & PS_CSC) { + x.errors = 0; /* a real plug or unplug: start counting afresh */ + x.gave_up = 0; + wr(off, (ps & PS_KEEP) | (ps & PS_CHANGES)); /* clear the change bits (RW1C) */ + } + if (ps & PS_CCS) + any = 1; + } + if (!any) + return; /* every port empty: keep waiting for the next change */ + if (x.errors > KBD_ERR_MAX) { + if (!x.gave_up) { + x.gave_up = 1; + ck_printf("keyboard: gave up after %u tries; unplug it and plug it back in\n", x.errors); + } + return; + } + forget_devices(); + x.why = ""; + int ok = scan_ports() == 0; + uint32_t ev[4]; + while (ev_next(ev)) /* events raised by our own resets; a report that already came back is re-armed */ + if (ok && ev_type(ev) == T_EV_TRANSFER && (ev[3] >> 24) == x.kbd->slot && ((ev[3] >> 16) & 0x1fu) == x.dci) + arm(); + if (ok) { + kbd_ready(); + return; + } + x.errors++; + x.rescan = x.errors <= KBD_ERR_MAX; /* try again on the next poll, up to the limit */ + ck_printf("keyboard: not found after replug (%s, completion %u; try %u of %u)\n", x.why, x.last_code, x.errors, + KBD_ERR_MAX + 1u); +} + void ck_x86_kbd_hold_poll(uint64_t *end) { - if (!ck_x86_kbd_ready() || !poll_keys()) + if (!x.kbd || !x.kbd_port) + return; + int got = poll_keys(); /* while stopped this only drains events and watches the ports */ + if (!x.rescan && !x.stopped) { + uint32_t s = rd(x.op + OP_PORTSC(x.kbd_port)); + if ((s & PS_CSC) || !(s & PS_CCS)) + x.rescan = 1; /* missed event, or none sent: the port itself says so */ + } else if (!x.rescan && any_connect_change()) + x.rescan = 1; /* stopped: something was plugged in or pulled somewhere */ + if (x.rescan) + kbd_rescan(); + if (!got) return; uint64_t want = ck_rdtsc() + (uint64_t)CK_X86_KBD_IDLE_S * hz; if (want > g_cap) diff --git a/scripts/.crumb b/scripts/.crumb index e1ec69d4..a3e0db29 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-31T02:43:29Z", + "compiled_at": "2026-10-31T02:58:08Z", "compiler": "crumb-compile/1", - "digest": "sha256:5b000b2f77cd62ae8ad2a113a1f77e486e3c974ad5ecc89150e6e54ad714a781", + "digest": "sha256:26606d0e8c4950a8c3c6e095c1420389acb5a4a1147b16b98c282db4c227d037", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 133, - "generated_at_commit": "00e555f6296726b12cbcb226b4de58838540c2be", - "source_tree": "sha256:faa99151e464c03feaef7f07143105e27823030748f91212f4ec2c36bfccb0a3" + "generated_at_commit": "66bf338dd2c1ce4cf01f7f43094a939a33d1933a", + "source_tree": "sha256:222753c1362fb664e9d68a84113e34410a0eec5a1999c2135052abe9b513b221" }, "owner_lane": "", "provenance": { diff --git a/scripts/qemu_ck_allen_memory_test.sh b/scripts/qemu_ck_allen_memory_test.sh index 91f11a6a..27443e22 100755 --- a/scripts/qemu_ck_allen_memory_test.sh +++ b/scripts/qemu_ck_allen_memory_test.sh @@ -20,7 +20,7 @@ # first ("Welcome back, Drake. I still remember 1 thing you taught me, # and your 1 note."), answers "what is my favorite color", "what is # the gate code" and "how many times have you restarted" from the -# disk, then goodbye. +# disk, then goodbye (Allen sleeps; QEMU is then stopped). # other a copy of the disk after boot 1 on another machine, under a model # on no list ("WDC WD10EZEX"): the section alone makes it Allen's, # memory and the note load (booting anywhere). @@ -136,11 +136,11 @@ say() { echo "sendkey ret" >&3 exec 3>&- } -off() { # name: wait for QEMU to power off by itself after goodbye - local i - for i in $(seq 1 300); do running "$1" || return 0; sleep 1; done +off() { # name: after goodbye Allen sleeps (the kernel says so within a few seconds); then QEMU is stopped + local r=1 + wait_for "$1" 60 '^power: Allen asleep' && r=0 stop "$1" - return 1 + return $r } ready='^keyboard: type a line and press Enter' @@ -186,8 +186,8 @@ else fail "1: the note was not written first" fi chk "1: goodbye saves the line count" "${work}/one.txt" '^allen_memory: saved generation 5 to copy [AB] \(1 fact, 1 note\)' -chk "1: ACPI S5 power off" "${work}/one.txt" '^power: off via ACPI S5 ' -[[ ${b1_off} == 1 ]] && pass "1: QEMU powered off by itself" || fail "1: QEMU still running" +chk "1: Allen asleep after goodbye" "${work}/one.txt" '^power: Allen asleep' +[[ ${b1_off} == 1 ]] && pass "1: sleep seen before QEMU was stopped" || fail "1: no sleep after goodbye" nochk "1: no write refused by the fence" "${work}/one.txt" 'ahci_write: .*refused' nochk "1: no failed save" "${work}/one.txt" 'save FAILED' @@ -251,7 +251,7 @@ txt two >"${work}/two.txt" txt other >"${work}/other.txt" txt fresh >"${work}/fresh.txt" -echo "== boot 2: the same disk after a power off ==" +echo "== boot 2: the same disk after a stop ==" chk "2: Allen's section found" "${work}/two.txt" '^allen_memory: Allen'"'"'s section is on disk [0-9]+ \([0-9]+ blocks of 512 bytes\)$' chk "2: AIENOS partition found, not added again" "${work}/two.txt" '^allen_memory: AIENOS partition found, entry [0-9]+, first_lba='"${pf:-x}"' last_lba='"${pl:-x}"'$' nochk "2: no second partition" "${work}/two.txt" 'AIENOS partition added' @@ -262,8 +262,8 @@ chk "2: Allen welcomes Drake back first" "${work}/two.txt" '^allen: Welcome back chk "2: the fact remembered across the power off" "${work}/two.txt" '^allen: Your favorite color is blue\.$' chk "2: the note handed back across the power off" "${work}/two.txt" '^allen: From your notes: the gate code is 4471\.$' chk "2: the start count remembered" "${work}/two.txt" "^allen: This is start number 2 for me, and I've answered [0-9]+ lines in all\.\$" -chk "2: ACPI S5 power off" "${work}/two.txt" '^power: off via ACPI S5 ' -[[ ${b2_off} == 1 ]] && pass "2: QEMU powered off by itself" || fail "2: QEMU still running" +chk "2: Allen asleep after goodbye" "${work}/two.txt" '^power: Allen asleep' +[[ ${b2_off} == 1 ]] && pass "2: sleep seen before QEMU was stopped" || fail "2: no sleep after goodbye" nochk "2: no write refused by the fence" "${work}/two.txt" 'ahci_write: .*refused' echo "== other: the same section on another machine, under a model on no list ==" diff --git a/scripts/qemu_ck_imac_bootdisk_test.sh b/scripts/qemu_ck_imac_bootdisk_test.sh index 9cc4bf4e..815871ba 100755 --- a/scripts/qemu_ck_imac_bootdisk_test.sh +++ b/scripts/qemu_ck_imac_bootdisk_test.sh @@ -13,7 +13,7 @@ # start 1 stick (NETLDR.EFI) + network: the server offers the signed # default kernel; it adds Allen's section and the boot section # (EFI System Partition, 256 MiB) in unused space, installs itself -# as \EFI\BOOT\BOOTX64.EFI (slot A), reports boot_time; goodbye. +# as \EFI\BOOT\BOOTX64.EFI (slot A), reports boot_time; goodbye (Allen sleeps). # Host: fsck.fat finds nothing to repair, mtools reads BOOTX64.EFI # equal to the kernel image, the old partition and the stick are # byte-identical. @@ -137,9 +137,9 @@ say() { # name "lower-case words": typed through the QEMU monitor, then Enter echo "sendkey ret" >&3 exec 3>&- } -off() { local i; for i in $(seq 1 300); do running "$1" || return 0; sleep 1; done; stop "$1"; return 1; } +off() { wait_for "$1" 60 '^power: Allen asleep'; } # after goodbye Allen sleeps; run() then stops QEMU ready='^keyboard: type a line and press Enter' -run() { # name with-stick: start, wait for Allen, goodbye, power off; result in name.txt +run() { # name with-stick: start, wait for Allen, goodbye (he sleeps), stop; result in name.txt start "$1" "$2" if wait_for "$1" 400 "${ready}"; then say "$1" "goodbye" @@ -161,7 +161,7 @@ chk "1: Allen's section added" "${work}/one.txt" '^allen_memory: AIENOS partitio chk "1: boot section added in unused space" "${work}/one.txt" '^boot_disk: boot section added, entry [0-9]+, first_lba=[0-9]+ last_lba=[0-9]+ \(256 MiB, EFI System Partition\); the existing partitions were not touched$' chk "1: installed in slot A, read back" "${work}/one.txt" "^boot_disk: installed this kernel \\(commit ${commit:0:12}, generation [0-9]+, [0-9]+ bytes\\) as .EFI.BOOT.BOOTX64\\.EFI, slot A, new FAT32 volume, [0-9]+ blocks in [0-9]+ ms, read back exact; " chk "1: boot times reported with the loader" "${work}/one.txt" '^boot_time: since power on: firmware until the loader [0-9]+ ms, loader [0-9]+ ms, kernel [0-9]+ ms; Allen.s window at [0-9]+ ms$' -chk "1: powered off after goodbye" "${work}/one.txt" '^power: off via ACPI S5 ' +chk "1: Allen asleep after goodbye" "${work}/one.txt" '^power: Allen asleep' nochk "1: no write refused by the fence" "${work}/one.txt" 'ahci_write: .*refused' first="$(grep -aoE '^boot_disk: boot section added, entry [0-9]+, first_lba=[0-9]+' "${work}/one.txt" | grep -oE '[0-9]+$' || echo 0)" if [[ "${first}" -gt 0 ]]; then diff --git a/scripts/qemu_ck_imac_kernel_test.sh b/scripts/qemu_ck_imac_kernel_test.sh index dbe027fa..59280fcf 100755 --- a/scripts/qemu_ck_imac_kernel_test.sh +++ b/scripts/qemu_ck_imac_kernel_test.sh @@ -97,7 +97,7 @@ run() { # name, -cpu model, expected APIC mode -drive if=none,id=esp,format=raw,file="${img}" -device ide-hd,drive=esp,bus=ide.0 \ -drive if=none,id=data,format=raw,file="${data}" -device ide-hd,drive=data,bus=ide.1 \ -drive if=none,id=nvm,format=raw,file="${nvm}" -device nvme,drive=nvm,serial=AIENOSQEMU \ - -audiodev "${audio}" -device ich9-intel-hda -device hda-output,audiodev=snd0 \ + -audiodev "${audio}" -device ich9-intel-hda -device hda-duplex,audiodev=snd0 \ -display none -nic none -serial file:"${log}" -no-reboot & qpid=$! local self_exit=0 @@ -140,10 +140,13 @@ run() { # name, -cpu model, expected APIC mode chk "${name}: the night began at boot" "${txt}" "^screen: night: the sky made in [0-9]+ ms \([0-9]+ MiB drawing memory\); stars, black holes, then Allen\$" chk "${name}: sound controller found" "${txt}" "^pci: sound [0-9a-f:.]+ id=8086:293e class=0403[0-9a-f]{2} " chk "${name}: sound controller looked at" "${txt}" "^sound: ctrl=0 version=1\\.0 streams out=[1-9][0-9]* " - chk "${name}: codec mapped through the command rings" "${txt}" "^sound: codec=0 id=1af4:[0-9a-f]{4} sub=[0-9a-f]{4}:[0-9a-f]{4} rev=0x[0-9a-f]{8} afg=1 power=D0 widgets=0x02\\.\\.0x03 " + chk "${name}: codec mapped through the command rings" "${txt}" "^sound: codec=0 id=1af4:[0-9a-f]{4} sub=[0-9a-f]{4}:[0-9a-f]{4} rev=0x[0-9a-f]{8} afg=1 power=D0 widgets=0x02\\.\\.0x05 " chk "${name}: output path opened" "${txt}" "^sound: ctrl=0 opened 1 output pin\\(s\\): codec 0 pins 0x03\\(line\\)<-0x02\$" chk "${name}: chirp stream running" "${txt}" "^sound: ctrl=0 stream 4 playing the chirp from night [0-9]+ ms .* position after 2 ms [1-9][0-9]* bytes, status 0x[0-9a-f]{2}\$" chk "${name}: chirp stream stopped after the chirp" "${txt}" "^sound: chirp over; stream stopped at night [0-9]+ ms " + chk "${name}: microphone path opened" "${txt}" "^sound: codec=0 microphone: pin 0x05 \\(line in\\) -> converter 0x04\$" + chk "${name}: microphone stream recording" "${txt}" "^sound: ctrl=0 stream 0 recording 1000 ms from the microphone \\(pin 0x05 -> converter 0x04, format 0x0011, 192000 bytes\\); position after 2 ms [0-9]+ bytes, status 0x[0-9a-f]{2}\$" + chk "${name}: microphone recording summed up" "${txt}" "^sound: microphone recorded 1000 ms: 96000 samples, [0-9]+% nonzero \\(first at [0-9]+\\), peak [0-9]+, rms [0-9]+, dc -?[0-9]+ \\(16-bit scale\\), position [0-9]+ bytes, status 0x[0-9a-f]{2}\$" chk "${name}: no Ethernet in this VM" "${txt}" "^net: no Ethernet controller\$" chk "${name}: storage summary" "${txt}" "^storage: pci_functions=[1-9][0-9]* ahci_controllers=1 disks=2 nvme_controllers=1 nvme_disks=1 gpt_valid=2 writes=none\$" chk "${name}: one-line summary" "${txt}" "^summary: cores=4/4 timer=ok sata_disks=2 nvme_disks=1 gpt_valid=2 writes=none net=none\$" diff --git a/scripts/qemu_ck_imac_keyboard_test.sh b/scripts/qemu_ck_imac_keyboard_test.sh index 0bac5b63..9874449a 100755 --- a/scripts/qemu_ck_imac_keyboard_test.sh +++ b/scripts/qemu_ck_imac_keyboard_test.sh @@ -8,7 +8,8 @@ # hub a usb-kbd behind a usb-hub (the shape of Apple's wired keyboards, which # carry their own hub); keys are typed from OUTSIDE the guest through the # QEMU monitor ("sendkey"): "Hello Allen" Enter, "xy" Backspace "z?!," Enter, then -# after 70 s "goodbye" Enter. +# after 70 s "goodbye" Enter (Allen sleeps), the power button (system_powerdown) +# wakes him and taps him back to sleep, a key wakes him. # The kernel must find the keyboard behind the hub (QEMU numbers its USB 2 # ports after the USB 3 ones, so "port=1.1" shows as e.g. 5.1), echo both lines as # "keyboard_line: Hello Allen" and "keyboard_line: xz?!,", have Allen answer them @@ -16,7 +17,7 @@ # content-free "screen: Allen answered (11 characters in, 15 out)"), switch the # screen to Allen's window (a QEMU screendump of it is kept as # $out/allen-qemu.png), keep it up with no idle countdown (still on 70 s -# after the last key), answer "goodbye" and then power QEMU off by itself; +# after the last key), sleep on "goodbye", wake on the power button or a key; # direct a usb-kbd on a root port: found on that port; # none the controller with nothing on it: "keyboard: none (no USB keyboard # found)" and the normal boot otherwise. @@ -100,7 +101,7 @@ running() { local v="pid_$1"; kill -0 "${!v}" 2>/dev/null; } stop() { local v="pid_$1"; kill "${!v}" 2>/dev/null || true; } start hub -device usb-hub,bus=xhci.0,port=1 -device usb-kbd,bus=xhci.0,port=1.1 -start direct -device usb-kbd,bus=xhci.0,port=1 +start direct -device usb-kbd,bus=xhci.0,port=1,id=kbd0 start none # Keys go in through the QEMU monitor (outside the guest), 0.15 s apart. @@ -119,33 +120,77 @@ if wait_for hub 300 '^keyboard: type a line and press Enter'; then fi for k in x y backspace z shift-slash shift-1 comma ret; do echo "sendkey ${k}" >&3; sleep 0.15; done fi +# direct: unplug the keyboard from outside the guest, plug one back in, type on it. +replug_ok=0 +if wait_for direct 300 '^keyboard: type a line and press Enter'; then + exec 4>"${work}/direct.mon.in" + echo "device_del kbd0" >&4 + if wait_for direct 30 '^keyboard: unplugged'; then + sleep 1 + echo "device_add usb-kbd,bus=xhci.0,port=1,id=kbd1" >&4 + for _ in $(seq 1 150); do + [[ $(txt direct | grep -acE '^keyboard: ready ') -ge 2 ]] && { replug_ok=1; break; } + sleep 0.2 + done + if [[ ${replug_ok} == 1 ]]; then + sleep 1 + for k in o k ret; do echo "sendkey ${k}" >&4; sleep 0.15; done + wait_for direct 60 '^keyboard_line: ok$' || true + fi + fi +fi wait_for direct 300 '^power: Allen.s window stays on' || true wait_for none 300 '^power: holding the screen' || true stop direct stop none # Allen's window has no idle countdown: 70 s after the last key (the text -# screen's hold is 60 s) the hub run must still be up. Then "goodbye" ends it. +# screen's hold is 60 s) the hub run must still be up. Then "goodbye" puts +# Allen to sleep; QEMU's power button (monitor system_powerdown) wakes him, +# taps him back to sleep, and a key wakes him without being typed. stayed=0 +slept=0; tap_woke=0; tap_slept=0; key_woke=0 if [[ ${typed_ok} == 1 ]] && wait_for hub 60 "^allen: I don't know that yet\."; then sleep 70 running hub && ! has hub '^power: off' && stayed=1 for k in g o o d b y e ret; do echo "sendkey ${k}" >&3; sleep 0.15; done + if wait_for hub 60 '^power: Allen asleep'; then + slept=1 + sleep 2 + echo "system_powerdown" >&3 + if wait_for hub 30 '^power: Allen awake'; then + tap_woke=1 + sleep 2 + echo "system_powerdown" >&3 + for _ in $(seq 1 150); do + [[ $(txt hub | grep -acE '^power: Allen asleep') -ge 2 ]] && { tap_slept=1; break; } + sleep 0.2 + done + if [[ ${tap_slept} == 1 ]]; then + sleep 2 + echo "sendkey x" >&3 + for _ in $(seq 1 150); do + [[ $(txt hub | grep -acE '^power: Allen awake') -ge 2 ]] && { key_woke=1; break; } + sleep 0.2 + done + sleep 2 + for k in o k ret; do echo "sendkey ${k}" >&3; sleep 0.15; done + wait_for hub 60 '^keyboard_line: ok$' || true + fi + fi + fi fi -# After goodbye the hub run must power off by itself (ACPI S5). -self_off=0 -for _ in $(seq 1 300); do # generous: three emulated machines share the host - if ! running hub; then has hub '^power: off via ACPI S5 ' && self_off=1; break; fi - sleep 1 -done stop hub + for r in hub direct none; do txt "${r}" >"${work}/${r}.txt"; done echo "== hub: usb-kbd behind usb-hub ==" chk "hub: controller running" "${work}/hub.txt" '^xhci: ctrl=0 running version=[0-9a-f]+ ports=[1-9][0-9]* slots=[1-8] context_bytes=(32|64) scratchpads=[0-9]+$' chk "hub: hub walked" "${work}/hub.txt" '^usb: port [0-9]+: hub, [1-9][0-9]* ports, (full|high) speed$' chk "hub: keyboard found behind the hub" "${work}/hub.txt" '^keyboard: ready \(controller 0, port [0-9]+\.1, full speed, slot [1-8], endpoint 0x8[1-9a-f]\)$' -chk "hub: typing prompt" "${work}/hub.txt" '^keyboard: type a line and press Enter; Allen.s window stays on until you type goodbye$' -chk "hub: no countdown while Allen's window is up" "${work}/hub.txt" '^power: Allen.s window stays on until goodbye \(or the power button\), then ACPI S5$' +chk "hub: typing prompt" "${work}/hub.txt" '^keyboard: type a line and press Enter; goodbye puts Allen to sleep, any key wakes him, holding the power button 4 s turns the computer off$' +chk "hub: no countdown while Allen's window is up" "${work}/hub.txt" '^power: Allen.s window stays on; goodbye or a power-button tap puts him to sleep, hold the button 4 s to turn off$' +chk "hub: power button watched" "${work}/hub.txt" '^power: button watched at PM1 status port 0x[0-9a-f]+ ' + [[ ${typed_ok} == 1 ]] && echo "PASS hub: keys sent from outside the guest" || { echo "FAIL hub: keys not sent"; fails=$((fails + 1)); } chk "hub: Allen's window took the screen" "${work}/hub.txt" '^screen: Allen.s window \([0-9]+x[0-9]+, [0-9]+ MiB drawing memory\)$' chk "hub: the night drawn by the secondary core, frames timed" "${work}/hub.txt" '^screen: night: [1-9][0-9]* frames before Allen woke, average [0-9]+\.[0-9] ms, slowest [0-9]+\.[0-9] ms \(drawn by a secondary core\)$' @@ -157,14 +202,24 @@ chk "hub: backspace edits the line; shifted and plain symbols typed" "${work}/hu chk "hub: Allen says what it does not know" "${work}/hub.txt" "^allen: I don't know that yet\." [[ ${stayed} == 1 ]] && echo "PASS hub: still on 70 s after the last key (no idle countdown)" || { echo "FAIL hub: Allen's window did not stay up"; fails=$((fails + 1)); } chk "hub: Allen says goodbye" "${work}/hub.txt" '^allen: Goodbye\. Until next time\.$' -chk "hub: typing session ended on its own line" "${work}/hub.txt" '^keyboard: done \(lines=3\)$' chk "hub: kernel alive" "${work}/hub.txt" '^kernel: alive$' -chk "hub: ACPI S5 power off" "${work}/hub.txt" '^power: off via ACPI S5 ' -[[ ${self_off} == 1 ]] && echo "PASS hub: QEMU powered off by itself after goodbye" || { echo "FAIL hub: QEMU still running"; fails=$((fails + 1)); } +# Goodbye sleeps instead of powering off; a 4 s hold is the chipset's own hard off and QEMU cannot hold the button. +[[ ${slept} == 1 ]] && echo "PASS hub: Allen asleep after goodbye" || { echo "FAIL hub: no sleep after goodbye"; fails=$((fails + 1)); } +[[ ${tap_woke} == 1 ]] && echo "PASS hub: power-button tap woke Allen" || { echo "FAIL hub: power-button tap did not wake Allen"; fails=$((fails + 1)); } +[[ ${tap_slept} == 1 ]] && echo "PASS hub: second tap put Allen to sleep" || { echo "FAIL hub: second tap did not sleep"; fails=$((fails + 1)); } +[[ ${key_woke} == 1 ]] && echo "PASS hub: a key woke Allen" || { echo "FAIL hub: key did not wake Allen"; fails=$((fails + 1)); } +# The earlier backspace test typed "xz?!,"; the waking x must not start a second x line. +if [[ $(grep -acE '^keyboard_line: x' "${work}/hub.txt") -gt 1 ]] || grep -aqE '^keyboard_line: xok$' "${work}/hub.txt"; then echo "FAIL hub: the waking key was typed"; fails=$((fails + 1)); else echo "PASS hub: the waking key was not typed"; fi +chk "hub: typing works again after waking" "${work}/hub.txt" '^keyboard_line: ok$' + echo "== direct: usb-kbd on a root port ==" chk "direct: keyboard found on a root port" "${work}/direct.txt" '^keyboard: ready \(controller 0, port [0-9]+, (full|high) speed, slot 1, endpoint 0x8[1-9a-f]\)$' -chk "direct: Allen's window stays on" "${work}/direct.txt" '^power: Allen.s window stays on until goodbye \(or the power button\), then ACPI S5$' +chk "direct: Allen's window stays on" "${work}/direct.txt" '^power: Allen.s window stays on; goodbye or a power-button tap puts him to sleep, hold the button 4 s to turn off$' + +chk "direct: unplug noticed" "${work}/direct.txt" '^keyboard: unplugged' +[[ ${replug_ok} == 1 ]] && echo "PASS direct: keyboard found again after replug" || { echo "FAIL direct: no second keyboard: ready after replug"; fails=$((fails + 1)); } +chk "direct: line typed on the replugged keyboard" "${work}/direct.txt" '^keyboard_line: ok$' echo "== none: controller, no keyboard ==" chk "none: controller found" "${work}/none.txt" '^pci: xhci [0-9a-f:.]+ id=1b36:000d ' ```