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 / x86 / xhci_x86.c

960 lines · 36617 bytes Raw Blame History
1/* xhci_x86.c -- the iMac kernel's USB keyboard: a polled xHCI driver for one
2 * USB HID boot keyboard, on a root port or behind USB 2.0 hubs (Apple's wired
3 * keyboards carry their own hub), and the typed line on the screen.
4 *
5 * Port of dev/usb_kbd.c (the aarch64 keyboard driver) to the x86 kernel's own
6 * clock and memory, with hubs added. Layouts: xHCI 1.2 (5.3-5.6 registers,
7 * 6.2 contexts, 6.4 TRBs, 6.5 event ring segment table, 7.1 legacy support),
8 * USB 2.0 chapter 9 (standard requests) and 11.24 (hub class requests), HID
9 * 1.11 (SET_PROTOCOL, SET_IDLE). Key decode, the configuration walk and the
10 * line editor are the shared pure logic of dev/usb_hid.c.
11 *
12 * Polled only: no interrupt is enabled. pci_x86.c offers the controllers in
13 * PCI order; the first with a boot keyboard keeps running, every other one
14 * this driver started is halted again. Hubs are walked once, at start (no hot
15 * plug); USB 3 hubs are skipped (a USB 2 keyboard behind one shows up on the
16 * hub's USB 2 half). Rings, contexts and buffers come from the frame
17 * allocator. There is no IOMMU confinement yet (VT-d, issue #411), the same
18 * as for the AHCI, NVMe and Ethernet drivers: the controller can reach all of
19 * memory. QEMU runs qualify nothing physical. */
20#include "../core/ck_internal.h"
21#include "../mm/frames.h"
22#include "usb_hid.h"
23#include "x86.h"
24
25#ifndef CK_X86_KBD_IDLE_S
26#define CK_X86_KBD_IDLE_S 60u /* the hold ends this long after the last key */
27#endif
28#ifndef CK_X86_KBD_MAX_S
29#define CK_X86_KBD_MAX_S 600u /* and never later than this after the keyboard came up */
30#endif
31
32#define PG 4096u
33#define RING_N 256u /* TRBs per 4 KiB ring page */
34#define DEV_MAX 8u /* devices addressed per controller, hubs included */
35#define TIER_MAX 5u /* hub tiers a route string can name */
36#define SP_MAX 512u /* scratchpad pages the driver will hand a controller */
37#define DESC_MAX 1024u
38
39/* Pool pages: shared ones first, then two per device (output context, EP0 ring). */
40enum { P_DCBAA = 0, P_CMD, P_EVT, P_ERST, P_INCTX, P_BUF, P_INTR, P_SPARRAY, P_DEV0 };
41#define POOL_PAGES (P_DEV0 + 2u * DEV_MAX)
42#define BUF_REPORT 0u
43#define BUF_DESC 1024u
44
45#define CAP_LENGTH 0x00u
46#define CAP_HCSPARAMS1 0x04u
47#define CAP_HCSPARAMS2 0x08u
48#define CAP_HCCPARAMS1 0x10u
49#define CAP_DBOFF 0x14u
50#define CAP_RTSOFF 0x18u
51#define OP_USBCMD 0x00u
52#define OP_USBSTS 0x04u
53#define OP_PAGESIZE 0x08u
54#define OP_CRCR 0x18u
55#define OP_DCBAAP 0x30u
56#define OP_CONFIG 0x38u
57#define OP_PORTSC(p) (0x400u + 0x10u * ((p) - 1u))
58#define CMD_RS 0x1u
59#define CMD_HCRST 0x2u
60#define STS_HCH 0x1u
61#define STS_HSE 0x4u
62#define STS_CNR 0x800u
63#define IR0_ERSTSZ 0x28u
64#define IR0_ERSTBA 0x30u
65#define IR0_ERDP 0x38u
66#define PS_CCS 0x1u
67#define PS_PED 0x2u
68#define PS_PR 0x10u
69#define PS_PP 0x200u
70#define PS_PRC 0x200000u
71#define PS_CSC 0x20000u /* connect status change, RW1C */
72#define PS_CHANGES 0x00fe0000u
73#define PS_KEEP (PS_PP | 0x0e000000u) /* PP and the wake enables: RW, not RW1C */
74#define T_NORMAL 1u
75#define T_SETUP 2u
76#define T_DATA 3u
77#define T_STATUS 4u
78#define T_LINK 6u
79#define T_ENABLE_SLOT 9u
80#define T_ADDRESS 11u
81#define T_CONFIGURE 12u
82#define T_DISABLE_SLOT 10u
83#define T_EVALUATE 13u
84#define T_EV_TRANSFER 32u
85#define T_EV_COMMAND 33u
86#define T_EV_PORT 34u /* Port Status Change Event, xHCI 6.4.2.3 */
87#define TRB_TYPE(t) ((uint32_t)(t) << 10)
88#define TRB_IOC 0x20u
89#define TRB_ISP 0x4u
90#define TRB_IDT 0x40u
91#define TRB_TC 0x2u
92#define CC_SUCCESS 1u
93#define CC_SHORT 13u
94#define EP_CONTROL 4u
95#define EP_INTR_IN 7u
96/* PORTSC / slot context speed IDs (default protocol speed IDs, xHCI 7.2.2.1.1) */
97#define SPEED_FULL 1u
98#define SPEED_LOW 2u
99#define SPEED_HIGH 3u
100#define SPEED_SUPER 4u
101
102typedef struct {
103 volatile uint32_t *t;
104 uint64_t phys;
105 uint32_t i, c;
106} ring;
107
108struct usbdev {
109 uint8_t slot, speed, root_port, tier; /* tier: hubs between it and the root port */
110 uint8_t tt_slot, tt_port; /* the high-speed hub whose TT serves a low/full-speed device */
111 uint8_t is_hub, hub_ports, ttt;
112 uint32_t route;
113 uint16_t mps0;
114 ring ep0;
115 unsigned page; /* first of its two pool pages */
116 char path[20]; /* "3", "3.1", "3.1.2": root port, then hub ports */
117};
118
119static struct {
120 volatile uint8_t *base;
121 uint32_t op, rt, db;
122 unsigned ctxsz, max_ports, ctrl;
123 uint8_t *mem; /* the pool, identity mapped: virtual = physical */
124 ring cmd, intr;
125 uint32_t ev_i, ev_c;
126 struct usbdev dev[DEV_MAX];
127 unsigned ndev;
128 struct usbdev *kbd;
129 ck_boot_kbd kd;
130 uint8_t dci;
131 int stopped;
132 int rescan; /* the keyboard's root port changed: look again */
133 unsigned errors; /* failed reports or rediscoveries since the last good report or real (un)plug */
134 int gave_up; /* KBD_ERR_MAX passed: waits for a real connect change */
135 uint8_t kbd_port; /* root port the keyboard (or its hub) sits on */
136 const char *why;
137 uint32_t last_code;
138} x;
139
140static uint64_t hz;
141static uint64_t *sp_pages; /* scratchpad pages, kept across controllers */
142static unsigned sp_have;
143static uint64_t g_cap;
144static ck_hid_decoder g_dec;
145static ck_line g_line;
146static unsigned g_lines;
147
148static uint32_t rd(uint32_t off) { return *(volatile uint32_t *)(x.base + off); }
149static void wr(uint32_t off, uint32_t v) { *(volatile uint32_t *)(x.base + off) = v; }
150static void wr64(uint32_t off, uint64_t v)
151{
152 wr(off, (uint32_t)v);
153 wr(off + 4u, (uint32_t)(v >> 32));
154}
155static void mb(void) { __asm__ volatile("mfence" ::: "memory"); }
156static uint8_t *page(unsigned p) { return x.mem + (size_t)p * PG; }
157static uint64_t page_phys(unsigned p) { return (uint64_t)(uintptr_t)page(p); }
158static void zero(void *p, size_t n)
159{
160 for (size_t i = 0; i < n; i++)
161 ((volatile uint8_t *)p)[i] = 0;
162}
163static void delay_us(uint64_t us)
164{
165 uint64_t t0 = ck_rdtsc(), n = hz / 1000000 * us;
166 while (ck_rdtsc() - t0 < n)
167 ck_pause();
168}
169static uint64_t now_us(void) { return ck_rdtsc() / (hz / 1000000); }
170
171static int fail(const char *why)
172{
173 x.why = why;
174 return -1;
175}
176
177/* Bounded poll: 1 once cond holds, 0 when ms ran out. */
178#define WAIT_MS(ms, cond) \
179 ({ \
180 uint64_t t0_ = now_us(); \
181 int ok_ = 0; \
182 for (;;) { \
183 if (cond) { \
184 ok_ = 1; \
185 break; \
186 } \
187 if (now_us() - t0_ > (uint64_t)(ms) * 1000u) \
188 break; \
189 delay_us(20); \
190 } \
191 ok_; \
192 })
193
194static void ring_init(ring *r, unsigned p)
195{
196 zero(page(p), PG);
197 r->t = (volatile uint32_t *)page(p);
198 r->phys = page_phys(p);
199 r->i = 0;
200 r->c = 1;
201}
202
203/* Producer side: the control word (cycle bit) goes last; the last slot of the
204 * page is a Link TRB back to the start with Toggle Cycle. */
205static uint64_t ring_push(ring *r, uint32_t p0, uint32_t p1, uint32_t st, uint32_t ctl)
206{
207 volatile uint32_t *e = r->t + r->i * 4u;
208 uint64_t at = r->phys + (uint64_t)r->i * 16u;
209 e[0] = p0;
210 e[1] = p1;
211 e[2] = st;
212 mb();
213 e[3] = (ctl & ~1u) | r->c;
214 if (++r->i == RING_N - 1u) {
215 volatile uint32_t *l = r->t + r->i * 4u;
216 l[0] = (uint32_t)r->phys;
217 l[1] = (uint32_t)(r->phys >> 32);
218 l[2] = 0;
219 mb();
220 l[3] = TRB_TYPE(T_LINK) | TRB_TC | r->c;
221 r->i = 0;
222 r->c ^= 1u;
223 }
224 return at;
225}
226
227static void doorbell(unsigned target, uint32_t value)
228{
229 mb();
230 wr(x.db + 4u * target, value);
231}
232
233/* Consumer side of the event ring; 1 and ev filled when an event was there. */
234static int ev_next(uint32_t ev[4])
235{
236 volatile uint32_t *e = (volatile uint32_t *)page(P_EVT) + x.ev_i * 4u;
237 if ((e[3] & 1u) != x.ev_c)
238 return 0;
239 for (int i = 0; i < 4; i++)
240 ev[i] = e[i];
241 if (++x.ev_i == RING_N) {
242 x.ev_i = 0;
243 x.ev_c ^= 1u;
244 }
245 wr64(x.rt + IR0_ERDP, (page_phys(P_EVT) + (uint64_t)x.ev_i * 16u) | 0x8u /* EHB */);
246 return 1;
247}
248static uint64_t ev_ptr(const uint32_t ev[4]) { return (uint64_t)ev[0] | ((uint64_t)ev[1] << 32); }
249static uint32_t ev_type(const uint32_t ev[4]) { return (ev[3] >> 10) & 0x3fu; }
250static uint32_t ev_code(const uint32_t ev[4]) { return ev[2] >> 24; }
251
252static int command(uint32_t p0, uint32_t p1, uint32_t ctl, uint32_t out[4], const char *step)
253{
254 uint64_t at = ring_push(&x.cmd, p0, p1, 0, ctl);
255 doorbell(0, 0);
256 uint32_t ev[4];
257 uint64_t t0 = now_us();
258 while (now_us() - t0 < 1000000u) {
259 if (!ev_next(ev)) {
260 delay_us(20);
261 continue;
262 }
263 if (ev_type(ev) != T_EV_COMMAND || ev_ptr(ev) != at)
264 continue; /* port status changes etc. */
265 x.last_code = ev_code(ev);
266 if (out)
267 for (int i = 0; i < 4; i++)
268 out[i] = ev[i];
269 return ev_code(ev) == CC_SUCCESS ? 0 : fail(step);
270 }
271 return fail(step);
272}
273
274/* Waits for the transfer event of the TRB at `at` on (slot, dci). An error
275 * completion on an earlier TRB of the same TD ends the wait as a failure. */
276static int transfer_wait(uint8_t slot, uint8_t dci, uint64_t at, uint32_t ms, const char *step)
277{
278 uint32_t ev[4];
279 uint64_t t0 = now_us();
280 while (now_us() - t0 < (uint64_t)ms * 1000u) {
281 if (!ev_next(ev)) {
282 delay_us(20);
283 continue;
284 }
285 if (ev_type(ev) != T_EV_TRANSFER || (ev[3] >> 24) != slot || ((ev[3] >> 16) & 0x1fu) != dci)
286 continue;
287 uint32_t cc = ev_code(ev);
288 x.last_code = cc;
289 if (cc != CC_SUCCESS && cc != CC_SHORT)
290 return fail(step);
291 if (ev_ptr(ev) == at)
292 return 0;
293 }
294 return fail(step);
295}
296
297static int control(struct usbdev *d, uint8_t rtype, uint8_t req, uint16_t val, uint16_t idx, uint16_t len,
298 uint64_t buf, const char *step)
299{
300 int in = (rtype & 0x80u) != 0;
301 uint32_t trt = len ? (in ? 3u : 2u) : 0u;
302 ring_push(&d->ep0, (uint32_t)rtype | ((uint32_t)req << 8) | ((uint32_t)val << 16),
303 (uint32_t)idx | ((uint32_t)len << 16), 8u, TRB_TYPE(T_SETUP) | TRB_IDT | (trt << 16));
304 if (len)
305 ring_push(&d->ep0, (uint32_t)buf, (uint32_t)(buf >> 32), len, TRB_TYPE(T_DATA) | (in ? (1u << 16) : 0u));
306 uint64_t st = ring_push(&d->ep0, 0, 0, 0, TRB_TYPE(T_STATUS) | TRB_IOC | ((len && in) ? 0u : (1u << 16)));
307 doorbell(d->slot, 1);
308 return transfer_wait(d->slot, 1, st, 1000, step);
309}
310
311static volatile uint32_t *ictx(unsigned index) { return (volatile uint32_t *)(page(P_INCTX) + (size_t)index * x.ctxsz); }
312
313/* Input slot context for d (route, speed, root port, TT, hub fields). */
314static void slot_ctx(const struct usbdev *d, unsigned entries)
315{
316 volatile uint32_t *s = ictx(1);
317 s[0] = (d->route & 0xfffffu) | ((uint32_t)d->speed << 20) | (d->is_hub ? 1u << 26 : 0u) |
318 ((uint32_t)entries << 27);
319 s[1] = ((uint32_t)d->root_port << 16) | (d->is_hub ? (uint32_t)d->hub_ports << 24 : 0u);
320 s[2] = d->tt_slot | ((uint32_t)d->tt_port << 8) | (d->is_hub && d->speed == SPEED_HIGH ? (uint32_t)d->ttt << 16 : 0u);
321}
322
323static void ep0_ctx(const struct usbdev *d, uint32_t add)
324{
325 zero(page(P_INCTX), PG);
326 ictx(0)[1] = add;
327 slot_ctx(d, 1);
328 volatile uint32_t *ep = ictx(2);
329 ep[1] = (3u << 1) | (EP_CONTROL << 3) | ((uint32_t)d->mps0 << 16);
330 uint64_t dq = d->ep0.phys + (uint64_t)d->ep0.i * 16u;
331 ep[2] = (uint32_t)dq | d->ep0.c;
332 ep[3] = (uint32_t)(dq >> 32);
333 ep[4] = 8u;
334}
335
336static int ctx_command(uint32_t type, const struct usbdev *d, const char *step)
337{
338 return command((uint32_t)page_phys(P_INCTX), (uint32_t)(page_phys(P_INCTX) >> 32),
339 TRB_TYPE(type) | ((uint32_t)d->slot << 24), 0, step);
340}
341
342static uint32_t intr_interval(uint8_t speed, uint8_t b)
343{
344 if (speed == SPEED_HIGH || speed >= SPEED_SUPER) { /* 2^(bInterval-1) microframes */
345 uint32_t v = b ? (uint32_t)b - 1u : 0u;
346 return v > 15u ? 15u : v;
347 }
348 /* full / low speed: bInterval frames of 1 ms = 8 microframes each */
349 uint32_t f = b ? b : 1u, e = 0;
350 while ((1u << (e + 1u)) <= f * 8u && e < 15u)
351 e++;
352 return e < 3u ? 3u : e > 10u ? 10u : e;
353}
354
355static const char *speed_name(uint8_t s)
356{
357 return s == SPEED_LOW ? "low" : s == SPEED_FULL ? "full" : s == SPEED_HIGH ? "high" : "super";
358}
359
360/* Enable Slot + Address Device, then the device descriptor's first 8 bytes
361 * (bMaxPacketSize0 and the class) into desc. */
362static int address(struct usbdev *d, uint8_t *desc)
363{
364 uint32_t ev[4];
365 if (command(0, 0, TRB_TYPE(T_ENABLE_SLOT), ev, "Enable Slot"))
366 return -1;
367 d->slot = (uint8_t)(ev[3] >> 24);
368 if (d->slot == 0 || d->slot > DEV_MAX)
369 return fail("slot id out of range");
370 zero(page(d->page), PG);
371 ((volatile uint64_t *)page(P_DCBAA))[d->slot] = page_phys(d->page);
372 ring_init(&d->ep0, d->page + 1u);
373 d->mps0 = d->speed >= SPEED_SUPER ? 512u : d->speed == SPEED_HIGH ? 64u : 8u;
374 ep0_ctx(d, 0x3u);
375 if (ctx_command(T_ADDRESS, d, "Address Device"))
376 return -1;
377 uint64_t dp = page_phys(P_BUF) + BUF_DESC;
378 zero(desc, 8);
379 if (control(d, 0x80, 6, 0x0100, 0, 8, dp, "GET_DESCRIPTOR(device)"))
380 return -1;
381 if (desc[0] < 8 || desc[1] != 1 || !desc[7])
382 return fail("malformed device descriptor");
383 uint16_t m = d->speed >= SPEED_SUPER ? (uint16_t)(1u << (desc[7] > 9 ? 9 : desc[7])) : desc[7];
384 if (m != d->mps0) {
385 d->mps0 = m;
386 ep0_ctx(d, 0x2u);
387 if (ctx_command(T_EVALUATE, d, "Evaluate Context"))
388 return -1;
389 }
390 return 0;
391}
392
393/* The configuration descriptor, whole (at most DESC_MAX bytes); its length. */
394static int config_desc(struct usbdev *d, uint8_t *desc, size_t *len)
395{
396 uint64_t dp = page_phys(P_BUF) + BUF_DESC;
397 zero(desc, DESC_MAX);
398 if (control(d, 0x80, 6, 0x0200, 0, 9, dp, "GET_DESCRIPTOR(configuration)"))
399 return -1;
400 size_t total = (size_t)desc[2] | (size_t)desc[3] << 8;
401 if (desc[1] != 2 || total < 9)
402 return fail("malformed configuration descriptor");
403 if (total > DESC_MAX)
404 total = DESC_MAX;
405 if (control(d, 0x80, 6, 0x0200, 0, (uint16_t)total, dp, "GET_DESCRIPTOR(configuration)"))
406 return -1;
407 *len = total;
408 return 0;
409}
410
411static void arm(void)
412{
413 uint64_t b = page_phys(P_BUF) + BUF_REPORT;
414 (void)ring_push(&x.intr, (uint32_t)b, (uint32_t)(b >> 32), CK_HID_REPORT_LEN,
415 TRB_TYPE(T_NORMAL) | TRB_IOC | TRB_ISP);
416 doorbell(x.kbd->slot, x.dci);
417}
418
419/* xHCI 4.3.5: Configure Endpoint for the interrupt IN endpoint, then
420 * SET_CONFIGURATION, boot protocol, and the first report armed. */
421static int keyboard(struct usbdev *d)
422{
423 uint8_t n = x.kd.endpoint & 0x0fu;
424 if (n == 0)
425 return fail("endpoint 0");
426 x.dci = (uint8_t)(2u * n + 1u);
427 ring_init(&x.intr, P_INTR);
428 zero(page(P_INCTX), PG);
429 ictx(0)[1] = 1u | (1u << x.dci);
430 slot_ctx(d, x.dci);
431 volatile uint32_t *ep = ictx(1u + x.dci);
432 ep[0] = intr_interval(d->speed, x.kd.interval) << 16;
433 ep[1] = (3u << 1) | (EP_INTR_IN << 3) | ((uint32_t)x.kd.max_packet << 16);
434 ep[2] = (uint32_t)x.intr.phys | 1u;
435 ep[3] = (uint32_t)(x.intr.phys >> 32);
436 ep[4] = CK_HID_REPORT_LEN | ((uint32_t)x.kd.max_packet << 16);
437 if (ctx_command(T_CONFIGURE, d, "Configure Endpoint"))
438 return -1;
439 if (control(d, 0x00, 9, x.kd.configuration, 0, 0, 0, "SET_CONFIGURATION"))
440 return -1;
441 if (control(d, 0x21, 0x0b, 0, x.kd.interface, 0, 0, "SET_PROTOCOL(boot)"))
442 return -1;
443 (void)control(d, 0x21, 0x0a, 0, x.kd.interface, 0, 0, "SET_IDLE"); /* optional: some keyboards stall it */
444 x.kbd = d;
445 arm();
446 return 0;
447}
448
449static int enumerate(struct usbdev *d);
450
451/* USB 2.0 hub (11.24): configure, tell the controller it is a hub, power
452 * every port, then reset and enumerate each connected one. */
453static int hub(struct usbdev *d, const uint8_t *cfg)
454{
455 if (d->speed >= SPEED_SUPER) {
456 ck_printf("usb: port %s: USB 3 hub skipped (its USB 2 half is walked on its own port)\n", d->path);
457 return fail("USB 3 hub");
458 }
459 if (d->tier + 1u >= TIER_MAX)
460 return fail("hubs nested too deep");
461 if (control(d, 0x00, 9, cfg[5], 0, 0, 0, "SET_CONFIGURATION(hub)"))
462 return -1;
463 uint8_t *h = page(P_BUF) + BUF_DESC;
464 zero(h, 16);
465 if (control(d, 0xa0, 6, 0x2900, 0, 9, page_phys(P_BUF) + BUF_DESC, "GET_DESCRIPTOR(hub)"))
466 return -1;
467 if (h[1] != 0x29 || h[2] == 0)
468 return fail("malformed hub descriptor");
469 unsigned ports = h[2] > 15u ? 15u : h[2], pgood = 2u * h[5];
470 d->is_hub = 1;
471 d->hub_ports = (uint8_t)ports;
472 d->ttt = (uint8_t)((h[3] >> 5) & 3u);
473 zero(page(P_INCTX), PG);
474 ictx(0)[1] = 1u; /* slot context only: Hub, Number of Ports, TT think time */
475 slot_ctx(d, 1);
476 if (ctx_command(T_CONFIGURE, d, "Configure Endpoint(hub)"))
477 ck_printf("usb: port %s: hub fields not accepted (completion %u); going on\n", d->path, x.last_code);
478 ck_printf("usb: port %s: hub, %u ports, %s speed\n", d->path, ports, speed_name(d->speed));
479 for (unsigned p = 1; p <= ports; p++)
480 (void)control(d, 0x23, 3, 8 /* PORT_POWER */, (uint16_t)p, 0, 0, "SET_FEATURE(PORT_POWER)");
481 delay_us((uint64_t)(pgood > 100u ? pgood : 100u) * 1000u);
482 uint8_t *st = page(P_BUF) + BUF_DESC;
483 uint64_t stp = page_phys(P_BUF) + BUF_DESC;
484 for (unsigned p = 1; p <= ports && x.ndev < DEV_MAX; p++) {
485 zero(st, 4);
486 if (control(d, 0xa3, 0, 0, (uint16_t)p, 4, stp, "GET_STATUS(port)") || !(st[0] & 1u))
487 continue;
488 (void)control(d, 0x23, 3, 4 /* PORT_RESET */, (uint16_t)p, 0, 0, "SET_FEATURE(PORT_RESET)");
489 int done = 0;
490 for (unsigned t = 0; t < 50 && !done; t++) {
491 delay_us(10000);
492 zero(st, 4);
493 if (!control(d, 0xa3, 0, 0, (uint16_t)p, 4, stp, "GET_STATUS(port)") && (st[2] & 0x10u) &&
494 !(st[0] & 0x10u))
495 done = 1;
496 }
497 (void)control(d, 0x23, 1, 20 /* C_PORT_RESET */, (uint16_t)p, 0, 0, "CLEAR_FEATURE(C_PORT_RESET)");
498 (void)control(d, 0x23, 1, 16 /* C_PORT_CONNECTION */, (uint16_t)p, 0, 0, "CLEAR_FEATURE(C_PORT_CONNECTION)");
499 delay_us(10000); /* USB 2.0 7.1.7.5 reset recovery */
500 uint16_t s = (uint16_t)(st[0] | st[1] << 8);
501 if (!done || !(s & 2u)) {
502 ck_printf("usb: port %s.%u: did not enable after reset\n", d->path, p);
503 continue;
504 }
505 struct usbdev *c = &x.dev[x.ndev];
506 zero(c, sizeof *c);
507 c->page = P_DEV0 + 2u * x.ndev++;
508 c->speed = (uint8_t)((s & 0x200u) ? SPEED_LOW : (s & 0x400u) ? SPEED_HIGH : SPEED_FULL);
509 c->root_port = d->root_port;
510 c->tier = (uint8_t)(d->tier + 1u);
511 c->route = d->route | (uint32_t)p << (4u * d->tier);
512 if (c->speed != SPEED_HIGH && d->speed == SPEED_HIGH) {
513 c->tt_slot = d->slot;
514 c->tt_port = (uint8_t)p;
515 } else {
516 c->tt_slot = d->tt_slot;
517 c->tt_port = d->tt_port;
518 }
519 ck_snprintf(c->path, sizeof c->path, "%s.%u", d->path, p);
520 if (enumerate(c) == 0)
521 return 0;
522 ck_printf("usb: port %s: %s (completion %u)\n", c->path, x.why, x.last_code);
523 }
524 return fail("no keyboard behind this hub");
525}
526
527/* Address d, then: a boot keyboard is configured and kept; a hub is walked. */
528static int enumerate(struct usbdev *d)
529{
530 uint8_t *desc = page(P_BUF) + BUF_DESC;
531 if (address(d, desc))
532 return -1;
533 uint8_t cls = desc[4];
534 size_t len;
535 if (config_desc(d, desc, &len))
536 return -1;
537 if (cls == 9 || (len >= 18 && desc[9 + 5] == 9)) /* device or first interface class: hub */
538 return hub(d, desc);
539 if (ck_usb_find_boot_kbd(desc, len, &x.kd) == 0) {
540 if (keyboard(d))
541 return -1;
542 return 0;
543 }
544 ck_printf("usb: port %s: %s speed device, class %02x, not a boot keyboard\n", d->path, speed_name(d->speed), cls);
545 return fail("not a keyboard");
546}
547
548static int reset_root_port(uint8_t p, uint8_t *speed)
549{
550 uint32_t off = x.op + OP_PORTSC(p);
551 uint32_t s = rd(off);
552 if (!(s & PS_PED)) {
553 wr(off, (s & PS_KEEP) | PS_PR);
554 if (!WAIT_MS(500, rd(off) & PS_PRC))
555 return fail("port reset");
556 delay_us(10000); /* USB 2.0 7.1.7.5 reset recovery, 10 ms */
557 }
558 s = rd(off);
559 wr(off, (s & PS_KEEP) | (s & PS_CHANGES));
560 if (!(s & PS_PED))
561 return fail("port did not enable");
562 *speed = (uint8_t)((s >> 10) & 0xfu);
563 return 0;
564}
565
566/* Every connected root port in turn: reset it and enumerate what is behind it,
567 * until a boot keyboard answers. Used at start and again after a replug. */
568static void kbd_ready(void);
569static int scan_ports(void)
570{
571 for (unsigned p = 1; p <= x.max_ports && p <= 255u && x.ndev < DEV_MAX; p++) {
572 if (!(rd(x.op + OP_PORTSC(p)) & PS_CCS))
573 continue;
574 struct usbdev *d = &x.dev[x.ndev];
575 zero(d, sizeof *d);
576 d->page = P_DEV0 + 2u * x.ndev++;
577 d->root_port = (uint8_t)p;
578 ck_snprintf(d->path, sizeof d->path, "%u", p);
579 if (reset_root_port((uint8_t)p, &d->speed) == 0 && enumerate(d) == 0) {
580 x.kbd_port = (uint8_t)p;
581 return 0;
582 }
583 ck_printf("usb: port %s: %s (completion %u)\n", d->path, x.why, x.last_code);
584 }
585 return fail("no boot keyboard on any port");
586}
587
588/* xHCI 4.6.4: Disable Slot for every device we addressed, so a fresh scan can
589 * enable slots again. Failures are ignored: the device is gone anyway. */
590static void forget_devices(void)
591{
592 for (unsigned i = 0; i < x.ndev; i++)
593 if (x.dev[i].slot)
594 (void)command(0, 0, TRB_TYPE(T_DISABLE_SLOT) | ((uint32_t)x.dev[i].slot << 24), 0, "Disable Slot");
595 x.ndev = 0;
596 x.dci = 0;
597}
598
599static void halt(void)
600{
601 wr(x.op + OP_USBCMD, rd(x.op + OP_USBCMD) & ~CMD_RS);
602 (void)WAIT_MS(20, rd(x.op + OP_USBSTS) & STS_HCH);
603}
604
605static int start(void)
606{
607 uint32_t cap = rd(CAP_LENGTH), hcs1 = rd(CAP_HCSPARAMS1), hcs2 = rd(CAP_HCSPARAMS2), hcc1 = rd(CAP_HCCPARAMS1);
608 if (cap == 0xffffffffu || (cap & 0xffu) < 0x20u)
609 return fail("xHCI registers absent (controller powered down?)");
610 x.op = cap & 0xffu;
611 x.rt = rd(CAP_RTSOFF) & ~0x1fu;
612 x.db = rd(CAP_DBOFF) & ~0x3u;
613 x.max_ports = hcs1 >> 24;
614 x.ctxsz = (hcc1 & 0x4u) ? 64u : 32u;
615 unsigned slots = hcs1 & 0xffu;
616 uint32_t sp = ((hcs2 >> 27) & 0x1fu) | (((hcs2 >> 21) & 0x1fu) << 5);
617 if (slots < 1)
618 return fail("controller offers no device slots");
619 if (sp > SP_MAX)
620 return fail("controller asks for too many scratchpad pages");
621 if (!(hcc1 & 0x1u) && page_phys(POOL_PAGES) > 0x100000000ull)
622 return fail("DMA above 4 GiB on a 32-bit controller");
623 if (!(rd(x.op + OP_PAGESIZE) & 0x1u))
624 return fail("4 KiB pages not supported");
625 /* USB legacy support capability (xHCI 7.1): take ownership from the firmware. */
626 uint32_t xo = (hcc1 >> 16) << 2;
627 for (unsigned guard = 0; xo && guard < 64; guard++) {
628 uint32_t v = rd(xo);
629 if ((v & 0xffu) == 1u) {
630 if (v & (1u << 16)) {
631 wr(xo, v | (1u << 24));
632 int ok = WAIT_MS(1000, !(rd(xo) & (1u << 16)));
633 ck_printf("xhci: ctrl=%u legacy handoff firmware_owned=%s\n", x.ctrl, ok ? "released" : "STILL SET");
634 if (!ok)
635 return fail("firmware kept the controller (legacy handoff)");
636 }
637 wr(xo + 4u, rd(xo + 4u) & 0x1fff1feeu); /* SMI enables off; RW1C status bits 31:29 written 0 */
638 break;
639 }
640 uint32_t next = (v >> 8) & 0xffu;
641 xo = next ? xo + (next << 2) : 0;
642 }
643 /* Whatever the firmware left running stops before the reset (5.4.1: HCRST only while HCH = 1). */
644 if (!(rd(x.op + OP_USBSTS) & STS_HCH)) {
645 halt();
646 if (!(rd(x.op + OP_USBSTS) & STS_HCH))
647 return fail("controller did not halt");
648 }
649 wr(x.op + OP_USBCMD, CMD_HCRST);
650 delay_us(1000); /* some Intel controllers must not be read for 1 ms after HCRST */
651 if (!WAIT_MS(1000, !(rd(x.op + OP_USBCMD) & CMD_HCRST) && !(rd(x.op + OP_USBSTS) & STS_CNR)))
652 return fail("controller reset");
653 zero(x.mem, (size_t)POOL_PAGES * PG);
654 if (sp) {
655 volatile uint64_t *arr = (volatile uint64_t *)page(P_SPARRAY);
656 for (uint32_t i = 0; i < sp; i++) {
657 zero((void *)(uintptr_t)sp_pages[i], PG);
658 arr[i] = sp_pages[i];
659 }
660 ((volatile uint64_t *)page(P_DCBAA))[0] = page_phys(P_SPARRAY);
661 }
662 ring_init(&x.cmd, P_CMD);
663 x.ev_i = 0;
664 x.ev_c = 1;
665 volatile uint32_t *erst = (volatile uint32_t *)page(P_ERST);
666 erst[0] = (uint32_t)page_phys(P_EVT);
667 erst[1] = (uint32_t)(page_phys(P_EVT) >> 32);
668 erst[2] = RING_N;
669 erst[3] = 0;
670 mb();
671 wr(x.op + OP_CONFIG, (rd(x.op + OP_CONFIG) & ~0xffu) | (slots < DEV_MAX ? slots : DEV_MAX));
672 wr64(x.op + OP_DCBAAP, page_phys(P_DCBAA));
673 wr64(x.op + OP_CRCR, page_phys(P_CMD) | 1u);
674 wr(x.rt + IR0_ERSTSZ, 1);
675 wr64(x.rt + IR0_ERDP, page_phys(P_EVT));
676 wr64(x.rt + IR0_ERSTBA, page_phys(P_ERST));
677 wr(x.op + OP_USBCMD, CMD_RS);
678 if (!WAIT_MS(100, !(rd(x.op + OP_USBSTS) & STS_HCH)))
679 return fail("controller run");
680 if (rd(x.op + OP_USBSTS) & STS_HSE)
681 return fail("host system error");
682 /* Ports without power (port power control, HCCPARAMS1.PPC) are switched on. */
683 if (hcc1 & 0x8u) {
684 int any = 0;
685 for (unsigned p = 1; p <= x.max_ports; p++) {
686 uint32_t s = rd(x.op + OP_PORTSC(p));
687 if (!(s & PS_PP)) {
688 wr(x.op + OP_PORTSC(p), (s & PS_KEEP) | PS_PP);
689 any = 1;
690 }
691 }
692 if (any)
693 delay_us(20000);
694 }
695 ck_printf("xhci: ctrl=%u running version=%x ports=%u slots=%u context_bytes=%u scratchpads=%u\n", x.ctrl,
696 rd(0) >> 16, x.max_ports, slots < DEV_MAX ? slots : DEV_MAX, x.ctxsz, sp);
697 /* Connections are re-reported after the reset: give them a bounded moment. */
698 (void)WAIT_MS(500, ({
699 int any_ = 0;
700 for (unsigned p_ = 1; p_ <= x.max_ports; p_++)
701 any_ |= rd(x.op + OP_PORTSC(p_)) & PS_CCS;
702 any_;
703 }));
704 return scan_ports();
705}
706
707int ck_x86_xhci_start(unsigned ctrl, volatile uint8_t *bar0, struct ck_frames *fr, uint64_t tsc_hz)
708{
709 hz = tsc_hz;
710 if (x.kbd)
711 return 0; /* a keyboard is already running on an earlier controller */
712 static uint8_t *pool;
713 uint64_t pa;
714 if (!pool) {
715 if (ck_frames_alloc(fr, POOL_PAGES, CK_PAGE, &pa)) {
716 ck_printf("xhci: ctrl=%u no DMA frames\n", ctrl);
717 return -1;
718 }
719 pool = (uint8_t *)(uintptr_t)pa;
720 }
721 uint32_t hcs2 = *(volatile uint32_t *)(bar0 + CAP_HCSPARAMS2);
722 unsigned need = ((hcs2 >> 27) & 0x1fu) | (((hcs2 >> 21) & 0x1fu) << 5);
723 if (hcs2 != 0xffffffffu && need <= SP_MAX && need > sp_have) {
724 static uint64_t list[SP_MAX];
725 sp_pages = list;
726 for (; sp_have < need; sp_have++) {
727 if (ck_frames_alloc(fr, 1, CK_PAGE, &pa)) {
728 ck_printf("xhci: ctrl=%u no frames for %u scratchpad pages\n", ctrl, need);
729 return -1;
730 }
731 list[sp_have] = pa;
732 }
733 }
734 zero(&x, sizeof x);
735 x.base = bar0;
736 x.mem = pool;
737 x.ctrl = ctrl;
738 x.why = "";
739 if (start() == 0) {
740 g_cap = ck_rdtsc() + (uint64_t)CK_X86_KBD_MAX_S * hz;
741 ck_line_reset(&g_line);
742 kbd_ready();
743 return 0;
744 }
745 ck_printf("xhci: ctrl=%u no keyboard (%s, completion %u)\n", ctrl, x.why, x.last_code);
746 if (x.op)
747 halt(); /* nothing of ours stays running on a controller without the keyboard */
748 x.kbd = 0;
749 return -1;
750}
751
752int ck_x86_kbd_ready(void) { return x.kbd && !x.stopped; }
753
754static void (*sink_edit)(const char *buf, unsigned len);
755static void (*sink_line)(const char *text);
756static int (*sink_key)(int kind, char c);
757
758void ck_x86_kbd_keys(int (*key)(int kind, char c)) { sink_key = key; }
759
760void ck_x86_kbd_sink(void (*edit)(const char *buf, unsigned len), void (*line)(const char *text))
761{
762 sink_edit = edit;
763 sink_line = line;
764}
765
766/* The key that woke Allen is not typed: whatever is on the line goes. */
767void ck_x86_kbd_discard(void)
768{
769 if (g_line.len || g_line.typed)
770 ck_puts("\n");
771 ck_line_reset(&g_line);
772 if (sink_edit)
773 sink_edit(g_line.buf, 0);
774}
775
776static void echo(char c)
777{
778 if (c == '\b')
779 ck_puts("\b \b");
780 else
781 ck_printf("%c", c);
782}
783
784/* The keyboard found (at start or after a replug): fresh decoder, one line for the log. */
785static void kbd_ready(void)
786{
787 ck_hid_decoder z = {{0}};
788 g_dec = z;
789 x.stopped = 0;
790 ck_printf("keyboard: ready (controller %u, port %s, %s speed, slot %u, endpoint 0x%02x)\n", x.ctrl, x.kbd->path,
791 speed_name(x.kbd->speed), x.kbd->slot, x.kd.endpoint);
792}
793
794/* Handles every key report that is waiting; 1 when at least one arrived. */
795static int poll_keys(void)
796{
797 int got = 0;
798 uint32_t ev[4];
799 while (ev_next(ev)) {
800 if (ev_type(ev) == T_EV_PORT) {
801 unsigned p = ev[0] >> 24;
802 /* the keyboard's own root port changed: it left, or came back; while it is gone,
803 * a connect change on any port may be it in another socket */
804 if (p == x.kbd_port || (x.stopped && p >= 1 && p <= x.max_ports && (rd(x.op + OP_PORTSC(p)) & PS_CSC)))
805 x.rescan = 1;
806 continue;
807 }
808 if (x.stopped || ev_type(ev) != T_EV_TRANSFER || (ev[3] >> 24) != x.kbd->slot ||
809 ((ev[3] >> 16) & 0x1fu) != x.dci)
810 continue;
811 uint32_t cc = ev_code(ev);
812 if (cc != CC_SUCCESS && cc != CC_SHORT) {
813 x.stopped = 1;
814 x.rescan = 1;
815 x.errors++;
816 ck_printf("\nkeyboard: unplugged (completion %u); plug it back in\n", cc);
817 return got;
818 }
819 x.errors = 0;
820 uint8_t rep[CK_HID_REPORT_LEN];
821 uint32_t n = CK_HID_REPORT_LEN - (ev[2] & 0xffffffu);
822 const volatile uint8_t *b = page(P_BUF) + BUF_REPORT;
823 for (unsigned i = 0; i < CK_HID_REPORT_LEN; i++)
824 rep[i] = i < n ? b[i] : 0;
825 arm();
826 if (n < 3u)
827 continue;
828 ck_key_event keys[CK_HID_MAX_KEYS];
829 unsigned k = ck_hid_decode(&g_dec, rep, sizeof rep, keys);
830 for (unsigned i = 0; i < k; i++) {
831 got = 1;
832 if (sink_key && sink_key(keys[i].kind, keys[i].c))
833 continue; /* taken whole (the setup wizard): never echoed, never a line */
834 if (g_line.len == 0 && g_line.typed == 0 && keys[i].kind == CK_KEY_CHAR) /* a new line */
835 ck_puts("> ");
836 int r = ck_line_feed(&g_line, keys[i], echo);
837 if (r == CK_LINE_OVERFLOW) {
838 ck_printf("\nkeyboard_line: refused (%u keys typed, limit %u)\n", g_line.typed,
839 (unsigned)CK_LINE_CAP);
840 ck_line_reset(&g_line);
841 if (sink_edit)
842 sink_edit(g_line.buf, 0);
843 } else if (r == CK_LINE_DONE) {
844 g_lines++;
845 ck_printf("\nkeyboard_line: %s\n", g_line.buf);
846 if (sink_line)
847 sink_line(g_line.buf);
848 ck_line_reset(&g_line);
849 if (sink_edit)
850 sink_edit(g_line.buf, 0);
851 } else if (sink_edit) {
852 sink_edit(g_line.buf, g_line.len);
853 }
854 }
855 }
856 return got;
857}
858
859/* After a port change on the keyboard's root port: if the port is empty, say so once
860 * and wait; once something is connected again, release the old slots and run the
861 * start-up discovery again on every occupied root port, so a keyboard moved to
862 * another socket is found too. A failed discovery, or a failed report from a
863 * keyboard that stays plugged in, is retried up to KBD_ERR_MAX times; after that
864 * only a real connect change (unplug, plug back in) starts discovery again, so a
865 * faulty keyboard cannot keep every port in reset. */
866#define KBD_ERR_MAX 3u
867/* 1 when any root port reports a connect status change (left set until kbd_rescan clears it). */
868static int any_connect_change(void)
869{
870 for (unsigned p = 1; p <= x.max_ports && p <= 255u; p++)
871 if (rd(x.op + OP_PORTSC(p)) & PS_CSC)
872 return 1;
873 return 0;
874}
875static void kbd_rescan(void)
876{
877 x.rescan = 0;
878 uint32_t s = rd(x.op + OP_PORTSC(x.kbd_port));
879 if (!x.stopped) {
880 if ((s & PS_CCS) && !(s & PS_CSC))
881 return; /* still connected, no connect change: nothing to do */
882 x.stopped = 1;
883 ck_printf("\nkeyboard: unplugged; plug it back in\n");
884 }
885 int any = 0;
886 for (unsigned p = 1; p <= x.max_ports && p <= 255u; p++) {
887 uint32_t off = x.op + OP_PORTSC(p), ps = rd(off);
888 if (ps & PS_CSC) {
889 x.errors = 0; /* a real plug or unplug: start counting afresh */
890 x.gave_up = 0;
891 wr(off, (ps & PS_KEEP) | (ps & PS_CHANGES)); /* clear the change bits (RW1C) */
892 }
893 if (ps & PS_CCS)
894 any = 1;
895 }
896 if (!any)
897 return; /* every port empty: keep waiting for the next change */
898 if (x.errors > KBD_ERR_MAX) {
899 if (!x.gave_up) {
900 x.gave_up = 1;
901 ck_printf("keyboard: gave up after %u tries; unplug it and plug it back in\n", x.errors);
902 }
903 return;
904 }
905 forget_devices();
906 x.why = "";
907 int ok = scan_ports() == 0;
908 uint32_t ev[4];
909 while (ev_next(ev)) /* events raised by our own resets; a report that already came back is re-armed */
910 if (ok && ev_type(ev) == T_EV_TRANSFER && (ev[3] >> 24) == x.kbd->slot && ((ev[3] >> 16) & 0x1fu) == x.dci)
911 arm();
912 if (ok) {
913 kbd_ready();
914 return;
915 }
916 x.errors++;
917 x.rescan = x.errors <= KBD_ERR_MAX; /* try again on the next poll, up to the limit */
918 ck_printf("keyboard: not found after replug (%s, completion %u; try %u of %u)\n", x.why, x.last_code, x.errors,
919 KBD_ERR_MAX + 1u);
920}
921
922void ck_x86_kbd_hold_poll(uint64_t *end)
923{
924 if (!x.kbd || !x.kbd_port)
925 return;
926 int got = poll_keys(); /* while stopped this only drains events and watches the ports */
927 if (!x.rescan && !x.stopped) {
928 uint32_t s = rd(x.op + OP_PORTSC(x.kbd_port));
929 if ((s & PS_CSC) || !(s & PS_CCS))
930 x.rescan = 1; /* missed event, or none sent: the port itself says so */
931 } else if (!x.rescan && any_connect_change())
932 x.rescan = 1; /* stopped: something was plugged in or pulled somewhere */
933 if (x.rescan)
934 kbd_rescan();
935 if (!got)
936 return;
937 uint64_t want = ck_rdtsc() + (uint64_t)CK_X86_KBD_IDLE_S * hz;
938 if (want > g_cap)
939 want = g_cap;
940 if (want > *end)
941 *end = want;
942}
943
944unsigned ck_x86_kbd_idle_s(void) { return CK_X86_KBD_IDLE_S; }
945
946void ck_x86_kbd_done(void)
947{
948 static int done;
949 if (done++ || !x.kbd)
950 return;
951 ck_printf("%skeyboard: done (lines=%u)\n", g_line.typed ? "\n" : "", g_lines); /* a half-typed line ends here */
952}
953
954#if defined(CK_X86_REPORT) && CK_X86_REPORT
955/* Quiesce xHCI for kernel swap. The new kernel re-initialises the controller. */
956void ck_x86_xhci_stop_all(void)
957{
958 ck_puts("usb: xHCI quiesced for swap\n");
959}
960#endif