interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / kernel / dev / usb_kbd.c

757 lines · 29953 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/* usb_kbd.c -- polled xHCI boot-keyboard driver, operator line input,
18 * console shell and recovery-access hook (see usb_kbd.h). Freestanding.
19 * Register and structure layouts: xHCI 1.2 (sections 5.3-5.6 registers,
20 * 6.2 contexts, 6.4 TRBs, 6.5 event ring segment table), USB 2.0 chapter 9
21 * (standard requests), HID 1.11 (SET_PROTOCOL, SET_IDLE). */
22#include "usb_kbd.h"
23#include "usb_hid.h"
24#include "ck.h"
25
26#define PG 4096u
27#define RING_N 256u /* TRBs per 4 KiB ring page */
28
29/* DMA region layout, one 4 KiB page each. */
30enum { P_DCBAA = 0, P_DEVCTX, P_INCTX, P_CMD, P_EVT, P_ERST, P_EP0, P_INTR, P_BUF, P_SPARRAY, P_SP0 };
31#define BUF_REPORT 0u
32#define BUF_DESC 512u
33#define DESC_MAX 255u
34
35/* Capability registers. */
36#define CAP_LENGTH 0x00u
37#define CAP_HCSPARAMS1 0x04u
38#define CAP_HCSPARAMS2 0x08u
39#define CAP_HCCPARAMS1 0x10u
40#define CAP_DBOFF 0x14u
41#define CAP_RTSOFF 0x18u
42/* Operational registers. */
43#define OP_USBCMD 0x00u
44#define OP_USBSTS 0x04u
45#define OP_PAGESIZE 0x08u
46#define OP_CRCR 0x18u
47#define OP_DCBAAP 0x30u
48#define OP_CONFIG 0x38u
49#define OP_PORTSC(p) (0x400u + 0x10u * ((p) - 1u))
50#define CMD_RS 0x1u
51#define CMD_HCRST 0x2u
52#define STS_HCH 0x1u
53#define STS_HSE 0x4u
54#define STS_CNR 0x800u
55/* Interrupter 0 (runtime base + 0x20). */
56#define IR0_ERSTSZ 0x28u
57#define IR0_ERSTBA 0x30u
58#define IR0_ERDP 0x38u
59/* PORTSC */
60#define PS_CCS 0x1u
61#define PS_PED 0x2u
62#define PS_PR 0x10u
63#define PS_PP 0x200u
64#define PS_PRC 0x200000u
65#define PS_CHANGES 0x00fe0000u
66#define PS_KEEP (PS_PP | 0x0e000000u) /* PP and the wake enables: RW, not RW1C */
67/* TRB types */
68#define T_NORMAL 1u
69#define T_SETUP 2u
70#define T_DATA 3u
71#define T_STATUS 4u
72#define T_LINK 6u
73#define T_ENABLE_SLOT 9u
74#define T_DISABLE_SLOT 10u
75#define T_ADDRESS 11u
76#define T_CONFIGURE 12u
77#define T_EVALUATE 13u
78#define T_EV_TRANSFER 32u
79#define T_EV_COMMAND 33u
80#define TRB_TYPE(t) ((uint32_t)(t) << 10)
81#define TRB_IOC 0x20u
82#define TRB_ISP 0x4u
83#define TRB_IDT 0x40u
84#define TRB_TC 0x2u
85#define CC_SUCCESS 1u
86#define CC_SHORT 13u
87/* Endpoint types (context) */
88#define EP_CONTROL 4u
89#define EP_INTR_IN 7u
90
91typedef struct {
92 volatile uint32_t *t;
93 uint64_t phys;
94 uint32_t i, c;
95} ring;
96
97typedef struct {
98 volatile uint8_t *base;
99 uint32_t op, rt, db;
100 uint8_t *mem;
101 uint64_t phys;
102 unsigned ctx, max_ports;
103 ring cmd, ep0, intr;
104 uint32_t ev_i, ev_c;
105 uint8_t slot, port, speed, dci;
106 uint16_t mps0;
107 ck_boot_kbd kbd;
108 int ep_halted;
109 const char *why;
110 uint32_t last_code;
111} kbd;
112
113static kbd g_k;
114static int g_offered; /* the recovery choice was offered (keyboard ready) */
115static int g_choice = -1; /* CK_RECOVERY_* once decided */
116
117static uint32_t rd(uint32_t off) { return *(volatile uint32_t *)(g_k.base + off); }
118static void wr(uint32_t off, uint32_t v) { *(volatile uint32_t *)(g_k.base + off) = v; }
119static void wr64(uint32_t off, uint64_t v)
120{
121 wr(off, (uint32_t)v);
122 wr(off + 4u, (uint32_t)(v >> 32));
123}
124static uint8_t *page(unsigned p) { return g_k.mem + (size_t)p * PG; }
125static uint64_t page_phys(unsigned p) { return g_k.phys + (uint64_t)p * PG; }
126static void zero(uint8_t *p, size_t n)
127{
128 for (size_t i = 0; i < n; i++) ((volatile uint8_t *)p)[i] = 0;
129}
130
131static int fail(int rc, const char *why)
132{
133 g_k.why = why;
134 return rc;
135}
136
137/* Bounded poll: returns 1 once cond() holds, 0 when ms ran out. */
138#define WAIT_MS(ms, cond) \
139 ({ \
140 uint64_t t0_ = ck_time_us(); \
141 int ok_ = 0; \
142 for (;;) { \
143 if (cond) { ok_ = 1; break; } \
144 if (ck_time_us() - t0_ > (uint64_t)(ms) * 1000u) break; \
145 ck_udelay(20); \
146 } \
147 ok_; \
148 })
149
150static void ring_init(ring *r, unsigned p)
151{
152 zero(page(p), PG);
153 r->t = (volatile uint32_t *)page(p);
154 r->phys = page_phys(p);
155 r->i = 0;
156 r->c = 1;
157}
158
159/* Producer side: writes the control word (cycle bit) last; the last slot of
160 * the page is a Link TRB back to the start with Toggle Cycle. */
161static uint64_t ring_push(ring *r, uint32_t p0, uint32_t p1, uint32_t st, uint32_t ctl)
162{
163 volatile uint32_t *e = r->t + r->i * 4u;
164 uint64_t at = r->phys + (uint64_t)r->i * 16u;
165 e[0] = p0;
166 e[1] = p1;
167 e[2] = st;
168 ck_mb();
169 e[3] = (ctl & ~1u) | r->c;
170 if (++r->i == RING_N - 1u) {
171 volatile uint32_t *l = r->t + r->i * 4u;
172 l[0] = (uint32_t)r->phys;
173 l[1] = (uint32_t)(r->phys >> 32);
174 l[2] = 0;
175 ck_mb();
176 l[3] = TRB_TYPE(T_LINK) | TRB_TC | r->c;
177 r->i = 0;
178 r->c ^= 1u;
179 }
180 return at;
181}
182
183static void doorbell(unsigned target, uint32_t value)
184{
185 ck_mb();
186 wr(g_k.db + 4u * target, value);
187}
188
189/* Consumer side of the event ring; 1 and ev filled when an event was there. */
190static int ev_next(uint32_t ev[4])
191{
192 volatile uint32_t *e = (volatile uint32_t *)page(P_EVT) + g_k.ev_i * 4u;
193 if ((e[3] & 1u) != g_k.ev_c) return 0;
194 for (int i = 0; i < 4; i++) ev[i] = e[i];
195 if (++g_k.ev_i == RING_N) {
196 g_k.ev_i = 0;
197 g_k.ev_c ^= 1u;
198 }
199 wr64(g_k.rt + IR0_ERDP, (page_phys(P_EVT) + (uint64_t)g_k.ev_i * 16u) | 0x8u /* EHB */);
200 return 1;
201}
202static uint64_t ev_ptr(const uint32_t ev[4]) { return (uint64_t)ev[0] | ((uint64_t)ev[1] << 32); }
203static uint32_t ev_type(const uint32_t ev[4]) { return (ev[3] >> 10) & 0x3fu; }
204static uint32_t ev_code(const uint32_t ev[4]) { return ev[2] >> 24; }
205
206static int command(uint32_t p0, uint32_t p1, uint32_t ctl, uint32_t out[4], const char *step)
207{
208 uint64_t at = ring_push(&g_k.cmd, p0, p1, 0, ctl);
209 doorbell(0, 0);
210 uint32_t ev[4];
211 uint64_t t0 = ck_time_us();
212 while (ck_time_us() - t0 < 1000000u) {
213 if (!ev_next(ev)) {
214 ck_udelay(20);
215 continue;
216 }
217 if (ev_type(ev) != T_EV_COMMAND || ev_ptr(ev) != at) continue; /* port status changes etc. */
218 g_k.last_code = ev_code(ev);
219 if (out)
220 for (int i = 0; i < 4; i++) out[i] = ev[i];
221 return ev_code(ev) == CC_SUCCESS ? 0 : fail(CK_KBD_E_FAILED, step);
222 }
223 return fail(CK_KBD_E_TIMEOUT, step);
224}
225
226/* Waits for the transfer event of the TRB at `at` on (slot, dci). An error
227 * completion on an earlier TRB of the same TD ends the wait as a failure. */
228static int transfer_wait(uint64_t at, uint8_t dci, uint32_t ms, const char *step)
229{
230 uint32_t ev[4];
231 uint64_t t0 = ck_time_us();
232 while (ck_time_us() - t0 < (uint64_t)ms * 1000u) {
233 if (!ev_next(ev)) {
234 ck_udelay(20);
235 continue;
236 }
237 if (ev_type(ev) != T_EV_TRANSFER || (ev[3] >> 24) != g_k.slot || ((ev[3] >> 16) & 0x1fu) != dci) continue;
238 uint32_t cc = ev_code(ev);
239 g_k.last_code = cc;
240 if (cc != CC_SUCCESS && cc != CC_SHORT) return fail(CK_KBD_E_FAILED, step);
241 if (ev_ptr(ev) == at) return 0;
242 }
243 return fail(CK_KBD_E_TIMEOUT, step);
244}
245
246static int control(uint8_t rtype, uint8_t req, uint16_t val, uint16_t idx, uint16_t len, uint64_t buf, const char *step)
247{
248 int in = (rtype & 0x80u) != 0;
249 uint32_t trt = len ? (in ? 3u : 2u) : 0u;
250 ring_push(&g_k.ep0, (uint32_t)rtype | ((uint32_t)req << 8) | ((uint32_t)val << 16), (uint32_t)idx | ((uint32_t)len << 16),
251 8u, TRB_TYPE(T_SETUP) | TRB_IDT | (trt << 16));
252 if (len)
253 ring_push(&g_k.ep0, (uint32_t)buf, (uint32_t)(buf >> 32), len, TRB_TYPE(T_DATA) | (in ? (1u << 16) : 0u));
254 uint64_t st = ring_push(&g_k.ep0, 0, 0, 0, TRB_TYPE(T_STATUS) | TRB_IOC | ((len && in) ? 0u : (1u << 16)));
255 doorbell(g_k.slot, 1);
256 return transfer_wait(st, 1, 1000, step);
257}
258
259static volatile uint32_t *ictx(unsigned index) { return (volatile uint32_t *)(page(P_INCTX) + (size_t)index * g_k.ctx); }
260
261static void ep0_context(uint32_t add, unsigned entries)
262{
263 zero(page(P_INCTX), PG);
264 ictx(0)[1] = add;
265 ictx(1)[0] = ((uint32_t)g_k.speed << 20) | ((uint32_t)entries << 27);
266 ictx(1)[1] = (uint32_t)g_k.port << 16;
267 volatile uint32_t *ep = ictx(2);
268 ep[1] = (3u << 1) | (EP_CONTROL << 3) | ((uint32_t)g_k.mps0 << 16);
269 uint64_t dq = g_k.ep0.phys + (uint64_t)g_k.ep0.i * 16u;
270 ep[2] = (uint32_t)dq | g_k.ep0.c;
271 ep[3] = (uint32_t)(dq >> 32);
272 ep[4] = 8u;
273}
274
275static uint32_t intr_interval(uint8_t speed, uint8_t b)
276{
277 if (speed >= 3) { /* high / super speed: 2^(bInterval-1) microframes */
278 uint32_t v = b ? (uint32_t)b - 1u : 0u;
279 return v > 15u ? 15u : v;
280 }
281 /* full / low speed: bInterval frames of 1 ms = 8 microframes each */
282 uint32_t f = b ? b : 1u, e = 0;
283 while ((1u << (e + 1u)) <= f * 8u && e < 15u) e++;
284 return e < 3u ? 3u : e > 10u ? 10u : e;
285}
286
287static int reset_port(uint8_t p)
288{
289 uint32_t off = g_k.op + OP_PORTSC(p);
290 uint32_t s = rd(off);
291 if (!(s & PS_PED)) {
292 wr(off, (s & PS_KEEP) | PS_PR);
293 if (!WAIT_MS(500, rd(off) & PS_PRC)) return fail(CK_KBD_E_TIMEOUT, "port reset");
294 ck_udelay(10000); /* USB 2.0 7.1.7.5 reset recovery, 10 ms */
295 }
296 s = rd(off);
297 wr(off, (s & PS_KEEP) | (s & PS_CHANGES));
298 if (!(s & PS_PED)) return fail(CK_KBD_E_UNSUP, "port did not enable");
299 g_k.speed = (uint8_t)((s >> 10) & 0xfu);
300 return 0;
301}
302
303static int attach(uint8_t p)
304{
305 int rc = reset_port(p);
306 if (rc) return rc;
307 g_k.port = p;
308 uint32_t ev[4];
309 if ((rc = command(0, 0, TRB_TYPE(T_ENABLE_SLOT), ev, "Enable Slot"))) return rc;
310 g_k.slot = (uint8_t)(ev[3] >> 24);
311 if (g_k.slot == 0) return fail(CK_KBD_E_UNSUP, "slot id 0");
312 zero(page(P_DEVCTX), PG);
313 ((volatile uint64_t *)page(P_DCBAA))[g_k.slot] = page_phys(P_DEVCTX);
314 ring_init(&g_k.ep0, P_EP0);
315 g_k.mps0 = g_k.speed == 4 ? 512u : g_k.speed == 3 ? 64u : 8u;
316 ep0_context(0x3u, 1);
317 if ((rc = command((uint32_t)page_phys(P_INCTX), (uint32_t)(page_phys(P_INCTX) >> 32),
318 TRB_TYPE(T_ADDRESS) | ((uint32_t)g_k.slot << 24), 0, "Address Device")))
319 return rc;
320 uint8_t *desc = page(P_BUF) + BUF_DESC;
321 uint64_t desc_phys = page_phys(P_BUF) + BUF_DESC;
322 zero(desc, DESC_MAX + 1u);
323 if ((rc = control(0x80, 6, 0x0100, 0, 8, desc_phys, "GET_DESCRIPTOR(device)"))) return rc;
324 if (desc[0] >= 8 && desc[1] == 1 && desc[7]) {
325 uint16_t m = g_k.speed == 4 ? (uint16_t)(1u << (desc[7] > 9 ? 9 : desc[7])) : desc[7];
326 if (m != g_k.mps0) {
327 g_k.mps0 = m;
328 ep0_context(0x2u, 1);
329 if ((rc = command((uint32_t)page_phys(P_INCTX), (uint32_t)(page_phys(P_INCTX) >> 32),
330 TRB_TYPE(T_EVALUATE) | ((uint32_t)g_k.slot << 24), 0, "Evaluate Context")))
331 return rc;
332 }
333 }
334 zero(desc, DESC_MAX + 1u);
335 if ((rc = control(0x80, 6, 0x0200, 0, DESC_MAX, desc_phys, "GET_DESCRIPTOR(configuration)"))) return rc;
336 if (ck_usb_find_boot_kbd(desc, DESC_MAX, &g_k.kbd)) return fail(CK_KBD_E_NOKBD, "no boot keyboard interface");
337 uint8_t n = g_k.kbd.endpoint & 0x0fu;
338 if (n == 0) return fail(CK_KBD_E_NOKBD, "endpoint 0");
339 g_k.dci = (uint8_t)(2u * n + 1u);
340 /* xHCI 4.3.5: Configure Endpoint, then SET_CONFIGURATION. */
341 ring_init(&g_k.intr, P_INTR);
342 zero(page(P_INCTX), PG);
343 ictx(0)[1] = 1u | (1u << g_k.dci);
344 ictx(1)[0] = ((uint32_t)g_k.speed << 20) | ((uint32_t)g_k.dci << 27);
345 ictx(1)[1] = (uint32_t)g_k.port << 16;
346 volatile uint32_t *ep = ictx(1u + g_k.dci);
347 ep[0] = intr_interval(g_k.speed, g_k.kbd.interval) << 16;
348 ep[1] = (3u << 1) | (EP_INTR_IN << 3) | ((uint32_t)g_k.kbd.max_packet << 16);
349 ep[2] = (uint32_t)g_k.intr.phys | 1u;
350 ep[3] = (uint32_t)(g_k.intr.phys >> 32);
351 ep[4] = CK_HID_REPORT_LEN | ((uint32_t)g_k.kbd.max_packet << 16);
352 if ((rc = command((uint32_t)page_phys(P_INCTX), (uint32_t)(page_phys(P_INCTX) >> 32),
353 TRB_TYPE(T_CONFIGURE) | ((uint32_t)g_k.slot << 24), 0, "Configure Endpoint")))
354 return rc;
355 if ((rc = control(0x00, 9, g_k.kbd.configuration, 0, 0, 0, "SET_CONFIGURATION"))) return rc;
356 if ((rc = control(0x21, 0x0b, 0, g_k.kbd.interface, 0, 0, "SET_PROTOCOL(boot)"))) return rc;
357 (void)control(0x21, 0x0a, 0, g_k.kbd.interface, 0, 0, "SET_IDLE"); /* optional: some keyboards stall it */
358 return 0;
359}
360
361static uint64_t g_armed;
362static void arm(void)
363{
364 g_armed = ring_push(&g_k.intr, (uint32_t)(page_phys(P_BUF) + BUF_REPORT), (uint32_t)((page_phys(P_BUF) + BUF_REPORT) >> 32),
365 CK_HID_REPORT_LEN, TRB_TYPE(T_NORMAL) | TRB_IOC | TRB_ISP);
366 doorbell(g_k.slot, g_k.dci);
367}
368
369/* One completed report into rep (8 bytes), or 0 when none is waiting. */
370static int poll_report(uint8_t rep[CK_HID_REPORT_LEN])
371{
372 uint32_t ev[4];
373 while (ev_next(ev)) {
374 if (ev_type(ev) != T_EV_TRANSFER || (ev[3] >> 24) != g_k.slot || ((ev[3] >> 16) & 0x1fu) != g_k.dci) continue;
375 uint32_t cc = ev_code(ev);
376 if (cc != CC_SUCCESS && cc != CC_SHORT) {
377 g_k.last_code = cc;
378 g_k.ep_halted = 1;
379 return 0;
380 }
381 uint32_t got = CK_HID_REPORT_LEN - (ev[2] & 0xffffffu);
382 const volatile uint8_t *b = page(P_BUF) + BUF_REPORT;
383 for (unsigned i = 0; i < CK_HID_REPORT_LEN; i++) rep[i] = i < got ? b[i] : 0;
384 arm();
385 return got >= 3u;
386 }
387 return 0;
388}
389
390static int start(volatile uint8_t *bar0, uint8_t *mem, uint64_t phys, size_t bytes)
391{
392 /* Fresh state per controller (the fence may try several, cut 2). */
393 for (size_t i = 0; i < sizeof g_k; i++) ((volatile uint8_t *)&g_k)[i] = 0;
394 g_k.base = bar0;
395 g_k.mem = mem;
396 g_k.phys = phys;
397 g_k.why = "";
398 if (!bar0 || !mem || bytes < (size_t)CK_KBD_DMA_PAGES * PG || (phys & (PG - 1u)))
399 return fail(CK_KBD_E_ARG, "DMA region too small or unaligned");
400 uint32_t cap = rd(CAP_LENGTH), hcs1 = rd(CAP_HCSPARAMS1), hcs2 = rd(CAP_HCSPARAMS2), hcc1 = rd(CAP_HCCPARAMS1);
401 if (cap == 0xffffffffu || (cap & 0xffu) < 0x20u) return fail(CK_KBD_E_ARG, "xHCI registers absent");
402 g_k.op = cap & 0xffu;
403 g_k.rt = rd(CAP_RTSOFF) & ~0x1fu;
404 g_k.db = rd(CAP_DBOFF) & ~0x3u;
405 g_k.max_ports = hcs1 >> 24;
406 g_k.ctx = (hcc1 & 0x4u) ? 64u : 32u;
407 uint32_t sp = ((hcs2 >> 27) & 0x1fu) | (((hcs2 >> 21) & 0x1fu) << 5);
408 if (sp > CK_KBD_MAX_SCRATCHPADS) return fail(CK_KBD_E_UNSUP, "controller asks for more scratchpad pages than the window holds");
409 if (!(hcc1 & 0x1u) && phys + bytes > 0x100000000ull) return fail(CK_KBD_E_UNSUP, "DMA above 4 GiB on a 32-bit controller");
410 if (!(rd(g_k.op + OP_PAGESIZE) & 0x1u)) return fail(CK_KBD_E_UNSUP, "4 KiB pages not supported");
411 /* USB legacy support capability (xHCI 7.1): take ownership from firmware. */
412 uint32_t x = (hcc1 >> 16) << 2;
413 for (unsigned guard = 0; x && guard < 64; guard++) {
414 uint32_t v = rd(x);
415 if ((v & 0xffu) == 1u) {
416 if (v & (1u << 16)) {
417 wr(x, v | (1u << 24));
418 int ok = WAIT_MS(1000, !(rd(x) & (1u << 16)));
419 ck_printf("xhci: legacy handoff bios_owned=%s\n", ok ? "released" : "STILL SET");
420 if (!ok) return fail(CK_KBD_E_TIMEOUT, "firmware kept the controller (legacy handoff)");
421 }
422 wr(x + 4u, rd(x + 4u) & 0x1fff1feeu); /* SMI enables off; RW1C status bits 31:29 written 0 */
423 break;
424 }
425 uint32_t next = (v >> 8) & 0xffu;
426 x = next ? x + (next << 2) : 0;
427 }
428 /* The fence left it halted; reset (5.4.1: HCRST only while HCH = 1). */
429 if (!(rd(g_k.op + OP_USBSTS) & STS_HCH)) return fail(CK_KBD_E_ARG, "controller not halted before reset");
430 wr(g_k.op + OP_USBCMD, CMD_HCRST);
431 if (!WAIT_MS(1000, !(rd(g_k.op + OP_USBCMD) & CMD_HCRST) && !(rd(g_k.op + OP_USBSTS) & STS_CNR)))
432 return fail(CK_KBD_E_TIMEOUT, "controller reset");
433 zero(mem, (size_t)CK_KBD_DMA_PAGES * PG);
434 if (sp) {
435 volatile uint64_t *arr = (volatile uint64_t *)page(P_SPARRAY);
436 for (uint32_t i = 0; i < sp; i++) arr[i] = page_phys(P_SP0 + i);
437 ((volatile uint64_t *)page(P_DCBAA))[0] = page_phys(P_SPARRAY);
438 }
439 ring_init(&g_k.cmd, P_CMD);
440 g_k.ev_i = 0;
441 g_k.ev_c = 1;
442 volatile uint32_t *erst = (volatile uint32_t *)page(P_ERST);
443 erst[0] = (uint32_t)page_phys(P_EVT);
444 erst[1] = (uint32_t)(page_phys(P_EVT) >> 32);
445 erst[2] = RING_N;
446 erst[3] = 0;
447 ck_mb();
448 wr(g_k.op + OP_CONFIG, (rd(g_k.op + OP_CONFIG) & ~0xffu) | 1u);
449 wr64(g_k.op + OP_DCBAAP, page_phys(P_DCBAA));
450 wr64(g_k.op + OP_CRCR, page_phys(P_CMD) | 1u);
451 wr(g_k.rt + IR0_ERSTSZ, 1);
452 wr64(g_k.rt + IR0_ERDP, page_phys(P_EVT));
453 wr64(g_k.rt + IR0_ERSTBA, page_phys(P_ERST));
454 wr(g_k.op + OP_USBCMD, CMD_RS);
455 if (!WAIT_MS(100, !(rd(g_k.op + OP_USBSTS) & STS_HCH))) return fail(CK_KBD_E_TIMEOUT, "controller run");
456 if (rd(g_k.op + OP_USBSTS) & STS_HSE) return fail(CK_KBD_E_FAILED, "host system error");
457 ck_printf("xhci: running ports=%u context_bytes=%u scratchpads=%u dma_pages=%u\n", g_k.max_ports, g_k.ctx, sp,
458 (unsigned)CK_KBD_DMA_PAGES);
459 /* Connections are re-reported after the reset: give them a bounded moment. */
460 (void)WAIT_MS(500, ({
461 int any_ = 0;
462 for (unsigned p_ = 1; p_ <= g_k.max_ports; p_++) any_ |= rd(g_k.op + OP_PORTSC(p_)) & PS_CCS;
463 any_;
464 }));
465 int rc = fail(CK_KBD_E_NOKBD, "no boot keyboard on any connected port");
466 for (unsigned p = 1; p <= g_k.max_ports && p <= 255u; p++) {
467 if (!(rd(g_k.op + OP_PORTSC(p)) & PS_CCS)) continue;
468 g_k.slot = 0;
469 rc = attach((uint8_t)p);
470 if (rc == 0) break;
471 ck_printf("keyboard: port %u not usable (%s, completion %u)\n", p, g_k.why, g_k.last_code);
472 if (g_k.slot) (void)command(0, 0, TRB_TYPE(T_DISABLE_SLOT) | ((uint32_t)g_k.slot << 24), 0, "Disable Slot");
473 g_k.slot = 0;
474 }
475 if (rc) return rc;
476 arm();
477 return 0;
478}
479
480static void echo(char c)
481{
482 if (c == '\b')
483 ck_puts("\b \b");
484 else
485 ck_printf("%c", c);
486}
487
488static void shell_out(const char *fmt, ...)
489{
490 va_list ap;
491 va_start(ap, fmt);
492 ck_vprintf(fmt, ap);
493 va_end(ap);
494}
495
496/* Next key event, waiting at most ms; 1 and *ev filled, or 0. */
497static int next_key(ck_hid_decoder *d, ck_key_event *pend, unsigned *npend, unsigned *ipend, uint32_t ms, ck_key_event *ev)
498{
499 uint64_t t0 = ck_time_us();
500 for (;;) {
501 if (*ipend < *npend) {
502 *ev = pend[(*ipend)++];
503 return 1;
504 }
505 uint8_t rep[CK_HID_REPORT_LEN];
506 if (poll_report(rep)) {
507 *npend = ck_hid_decode(d, rep, sizeof rep, pend);
508 *ipend = 0;
509 continue;
510 }
511 if (g_k.ep_halted || ck_time_us() - t0 >= (uint64_t)ms * 1000u) return 0;
512 ck_udelay(100);
513 }
514}
515
516int ck_kbd_phase(volatile uint8_t *bar0, uint8_t *mem, uint64_t phys, size_t bytes)
517{
518 int rc = start(bar0, mem, phys, bytes);
519 if (rc) {
520 ck_printf("keyboard: unavailable (%s, rc=%d, completion %u)\n", g_k.why, rc, g_k.last_code);
521 return rc;
522 }
523 ck_printf("keyboard: ready (port %u, slot %u, endpoint 0x%02x)\n", g_k.port, g_k.slot, g_k.kbd.endpoint);
524
525 ck_hid_decoder dec = {{0}};
526 ck_key_event pend[CK_HID_MAX_KEYS], ev = {0, 0};
527 unsigned np = 0, ip = 0;
528 /* Recovery access: bounded wait for one operator key. */
529 g_offered = 1;
530 ck_printf("recovery_access: waiting %u ms for an operator key (r = recovery console; any other key or no key = "
531 "normal boot)\n",
532 (unsigned)CK_KBD_RECOVERY_WAIT_MS);
533 int have = next_key(&dec, pend, &np, &ip, CK_KBD_RECOVERY_WAIT_MS, &ev);
534 g_choice = ck_recovery_decide(have, ev);
535 ck_printf("recovery_access: choice=%s\n", ck_recovery_name(g_choice));
536 if (g_choice == CK_RECOVERY_CONSOLE) return CK_KBD_OK; /* the fence revokes; devices.c runs the stub */
537 np = ip = 0;
538
539 ck_printf("keyboard: shell ready (%u s, idle %u s)\n", (unsigned)(CK_KBD_SHELL_MS / 1000u),
540 (unsigned)(CK_KBD_SHELL_IDLE_MS / 1000u));
541 ck_line line;
542 ck_line_reset(&line);
543 uint64_t t0 = ck_time_us();
544 const char *reason = "timeout";
545 ck_puts("aienos> ");
546 for (;;) {
547 uint64_t used = (ck_time_us() - t0) / 1000u;
548 if (used >= CK_KBD_SHELL_MS) break;
549 uint32_t left = (uint32_t)(CK_KBD_SHELL_MS - used);
550 if (!next_key(&dec, pend, &np, &ip, left < CK_KBD_SHELL_IDLE_MS ? left : CK_KBD_SHELL_IDLE_MS, &ev)) {
551 reason = g_k.ep_halted ? "endpoint halted" : (ck_time_us() - t0) / 1000u >= CK_KBD_SHELL_MS ? "timeout" : "idle";
552 break;
553 }
554 int r = ck_line_feed(&line, ev, echo);
555 if (r == CK_LINE_OVERFLOW) {
556 ck_printf("\nkeyboard_line: overflow (line refused: %u keys typed, limit %u)\n", line.typed, (unsigned)CK_LINE_CAP);
557 ck_puts("keyboard: done (overflow)\n");
558 ck_line_reset(&line);
559 ck_puts("aienos> ");
560 continue;
561 }
562 if (r != CK_LINE_DONE) continue;
563 ck_printf("\nkeyboard_echo: %s\nkeyboard_line: %s\nkeyboard: done (enter)\n", line.buf, line.buf);
564 ck_shell_ctx ctx = {ck_conventional_memory_kb(), ck_exception_level(), (ck_time_us() - t0) / 1000u, ck_commit()};
565 int ex = ck_shell_run(line.buf, &ctx, shell_out);
566 ck_line_reset(&line);
567 if (ex) {
568 reason = "exit";
569 break;
570 }
571 ck_puts("aienos> ");
572 }
573 ck_printf("\nkeyboard: done (%s)\n", reason);
574 return CK_KBD_OK;
575}
576
577void ck_kbd_recovery_report(const char *xhci_state)
578{
579 if (g_offered) return;
580 g_choice = CK_RECOVERY_NORMAL_TIMEOUT;
581 ck_printf("recovery_access: unavailable (no operator keyboard: xhci=%s); choice=normal reason=no-keyboard\n",
582 xhci_state ? xhci_state : "absent");
583}
584
585int ck_kbd_recovery_requested(void) { return g_choice == CK_RECOVERY_CONSOLE; }
586
587void ck_recovery_console_stub(void)
588{
589 uint8_t id[32];
590 char hex[65];
591 static const char hx[] = "0123456789abcdef";
592 ck_recovery_identity(ck_commit(), id);
593 for (int i = 0; i < 32; i++) {
594 hex[2 * i] = hx[id[i] >> 4];
595 hex[2 * i + 1] = hx[id[i] & 0xfu];
596 }
597 hex[64] = 0;
598 ck_puts("recovery_console: STUB (NEXT-PHASE-3 cut 1: the console itself is not built; no commands)\n");
599 ck_printf("recovery_console: identity build_sha256=%s commit=%s (image build identity; not an owner or machine "
600 "identity)\n",
601 hex, ck_commit());
602 ck_puts("recovery_console: halted (no device DMA live; power-cycle to leave)\n");
603 for (;;) {
604#if defined(__aarch64__)
605 __asm__ volatile("msr daifset, #0xf\n\twfi" ::: "memory");
606#endif
607 }
608}
609
610#if defined(CK_CONSOLE_SESSION) && CK_CONSOLE_SESSION
611/* ---- console session (C3-1a, QEMU test image only) ----
612 * Serial (PL011, polled) and the USB keyboard feed one bounded line editor
613 * and the same shell. No time limit, no idle exit: it ends on "exit". The USB
614 * half runs inside the xHCI fence (ck_kbd_session_phase); the serial half
615 * can also run alone (ck_console_session_serial_only) when the keyboard is
616 * unavailable or its endpoint halts. No new authority: the shell commands are
617 * the existing ones. */
618/* Most bytes the start-of-session drain reads before it gives up. */
619#define CK_SESSION_DRAIN_MAX 4096u
620static ck_line s_line;
621static ck_src_gate s_gate;
622static ck_hid_decoder s_dec;
623static ck_key_event s_pend[CK_HID_MAX_KEYS];
624static unsigned s_np, s_ip;
625static uint8_t s_prev;
626static int s_serial_ok, s_began, s_ended;
627static uint64_t s_t0;
628
629static const char *src_name(int s) { return s == CK_SRC_SERIAL ? "serial" : "usb"; }
630
631static void sess_begin(const char *usb)
632{
633 if (s_began) return;
634 s_began = 1;
635 uint32_t cr = 0;
636 s_serial_ok = ck_console_rx_ready(&cr);
637 if (s_serial_ok) {
638 /* Bytes typed before the session are not input. The drain is bounded: a
639 * continuous flood must not stall the boot. Error bytes (-2) are drained
640 * too; only an empty FIFO (-1) ends it early. */
641 unsigned n = 0;
642 while (n < CK_SESSION_DRAIN_MAX) {
643 if (ck_console_rx_poll() == -1) break;
644 n++;
645 }
646 if (n == CK_SESSION_DRAIN_MAX)
647 ck_printf("console_session: serial drain cap hit (%u bytes read, flood?); going on\n", n);
648 ck_printf("console_session: serial rx pl011 base=0x%llx uartcr=0x%04x ready\n",
649 (unsigned long long)ck_console_uart_base(), cr);
650 } else
651 ck_printf("console_session: serial rx unavailable (console uart is %s, uartcr=0x%04x)\n", ck_console_uart_name(), cr);
652 ck_printf("console_session: ready (usb %s; no time limit, no idle exit; ends on exit)\n", usb);
653 ck_line_reset(&s_line);
654 ck_src_gate_reset(&s_gate);
655 s_np = s_ip = 0;
656 s_t0 = ck_time_us();
657 ck_puts("console> ");
658}
659
660static void sess_drops(int owner, unsigned dropped)
661{
662 if (dropped)
663 ck_printf("console_input: dropped %u key(s) from %s while %s owned the line\n", dropped,
664 src_name(owner == CK_SRC_SERIAL ? CK_SRC_USB : CK_SRC_SERIAL), src_name(owner));
665}
666
667/* One key from src. Returns 1 when the shell ran "exit". */
668static int sess_key(int src, ck_key_event ev)
669{
670 if (!ck_src_gate_accept(&s_gate, src, ev)) return 0;
671 int r = ck_line_feed(&s_line, ev, echo);
672 if (r == CK_LINE_MORE && ev.kind != CK_KEY_ESCAPE) return 0;
673 int owner = s_gate.owner ? s_gate.owner : src; /* an unowned Enter or Escape: the key's own source */
674 if (r == CK_LINE_MORE && s_gate.owner == CK_SRC_NONE) return 0; /* Escape on an empty line: nothing to clear */
675 if (r == CK_LINE_OVERFLOW)
676 ck_printf("\nconsole_line: overflow (line refused: %u keys typed, limit %u) source=%s\n", s_line.typed,
677 (unsigned)CK_LINE_CAP, src_name(owner));
678 else if (r == CK_LINE_DONE)
679 ck_printf("\nconsole_echo: %s\nconsole_line: %s source=%s\n", s_line.buf, s_line.buf, src_name(owner));
680 else
681 ck_printf("\nconsole_line: cleared source=%s\n", src_name(owner));
682 sess_drops(owner, ck_src_gate_release(&s_gate));
683 int ex = 0;
684 if (r == CK_LINE_DONE) {
685 ck_shell_ctx ctx = {ck_conventional_memory_kb(), ck_exception_level(), (ck_time_us() - s_t0) / 1000u, ck_commit()};
686 ex = ck_shell_run(s_line.buf, &ctx, shell_out);
687 if (ex) ck_printf("console_session: exit (source=%s)\n", src_name(owner));
688 }
689 ck_line_reset(&s_line);
690 if (!ex) ck_puts("console> ");
691 return ex;
692}
693
694/* 0: the session ended (exit); 1: the USB endpoint halted, serial goes on. */
695static int sess_loop(int usb_ok)
696{
697 for (;;) {
698 int idle = 1;
699 if (usb_ok) {
700 if (s_ip < s_np) {
701 ck_key_event ev = s_pend[s_ip++];
702 idle = 0;
703 if (sess_key(CK_SRC_USB, ev)) { s_ended = 1; return 0; }
704 } else {
705 uint8_t rep[CK_HID_REPORT_LEN];
706 if (poll_report(rep)) {
707 s_np = ck_hid_decode(&s_dec, rep, sizeof rep, s_pend);
708 s_ip = 0;
709 idle = 0;
710 }
711 if (g_k.ep_halted) {
712 ck_printf("\nconsole_session: usb endpoint halted (completion %u); the keyboard is revoked, serial goes on\n",
713 g_k.last_code);
714 return 1;
715 }
716 }
717 }
718 if (s_serial_ok) {
719 int b = ck_console_rx_poll();
720 if (b == -2) idle = 0; /* errored byte: dropped by the console, look again at once */
721 if (b >= 0) {
722 idle = 0;
723 ck_key_event ev = ck_serial_key((uint8_t)b, &s_prev);
724 if (ev.kind != CK_KEY_NONE && sess_key(CK_SRC_SERIAL, ev)) { s_ended = 1; return 0; }
725 }
726 }
727 if (idle && usb_ok && !(rd(g_k.op + OP_PORTSC(g_k.port)) & PS_CCS)) {
728 ck_printf("\nconsole_session: usb keyboard disconnected (port %u); the keyboard is revoked, serial goes on\n", g_k.port);
729 return 1;
730 }
731 if (idle) ck_udelay(100);
732 }
733}
734
735int ck_kbd_session_phase(volatile uint8_t *bar0, uint8_t *mem, uint64_t phys, size_t bytes)
736{
737 int rc = start(bar0, mem, phys, bytes);
738 if (rc) {
739 ck_printf("console_session: usb keyboard unavailable (%s, rc=%d, completion %u)\n", g_k.why, rc, g_k.last_code);
740 return rc;
741 }
742 ck_printf("console_session: usb keyboard attached (port %u, slot %u, endpoint 0x%02x), inside the xHCI fence\n",
743 g_k.port, g_k.slot, g_k.kbd.endpoint);
744 sess_begin("keyboard ready");
745 (void)sess_loop(1);
746 return CK_KBD_OK;
747}
748
749void ck_console_session_serial_only(void)
750{
751 if (s_ended) return;
752 sess_begin("keyboard unavailable");
753 (void)sess_loop(0);
754}
755
756int ck_console_session_ended(void) { return s_ended; }
757#endif