source: mainline/uspace/drv/bus/usb/xhci/hc.c@ 2c0564c

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 2c0564c was 2c0564c, checked in by Ondřej Hlavatý <aearsis@…>, 8 years ago

xhci: handle potentially blocking events in separate fibril

  • Property mode set to 100644
File size: 28.3 KB
Line 
1/*
2 * Copyright (c) 2017 Ondrej Hlavaty
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup drvusbxhci
30 * @{
31 */
32/** @file
33 * @brief The host controller data bookkeeping.
34 */
35
36#include <errno.h>
37#include <str_error.h>
38#include <usb/debug.h>
39#include <usb/host/endpoint.h>
40#include "debug.h"
41#include "hc.h"
42#include "rh.h"
43#include "hw_struct/trb.h"
44#include "hw_struct/context.h"
45#include "endpoint.h"
46#include "transfers.h"
47#include "trb_ring.h"
48
49/**
50 * Default USB Speed ID mapping: Table 157
51 */
52#define PSI_TO_BPS(psie, psim) (((uint64_t) psim) << (10 * psie))
53#define PORT_SPEED(usb, mjr, psie, psim) { \
54 .name = "USB ", \
55 .major = mjr, \
56 .minor = 0, \
57 .usb_speed = USB_SPEED_##usb, \
58 .rx_bps = PSI_TO_BPS(psie, psim), \
59 .tx_bps = PSI_TO_BPS(psie, psim) \
60}
61
62static const xhci_port_speed_t default_psiv_to_port_speed [] = {
63 [1] = PORT_SPEED(FULL, 2, 2, 12),
64 [2] = PORT_SPEED(LOW, 2, 1, 1500),
65 [3] = PORT_SPEED(HIGH, 2, 2, 480),
66 [4] = PORT_SPEED(SUPER, 3, 3, 5),
67};
68
69static const unsigned usb_speed_to_psiv [] = {
70 [USB_SPEED_FULL] = 1,
71 [USB_SPEED_LOW] = 2,
72 [USB_SPEED_HIGH] = 3,
73 [USB_SPEED_SUPER] = 4,
74};
75
76/**
77 * Walk the list of extended capabilities.
78 *
79 * The most interesting thing hidden in extended capabilities is the mapping of
80 * ports to protocol versions and speeds.
81 */
82static int hc_parse_ec(xhci_hc_t *hc)
83{
84 unsigned psic, major, minor;
85 xhci_sp_name_t name;
86
87 xhci_port_speed_t *speeds = hc->speeds;
88
89 for (xhci_extcap_t *ec = hc->xecp; ec; ec = xhci_extcap_next(ec)) {
90 xhci_dump_extcap(ec);
91 switch (XHCI_REG_RD(ec, XHCI_EC_CAP_ID)) {
92 case XHCI_EC_USB_LEGACY:
93 assert(hc->legsup == NULL);
94 hc->legsup = (xhci_legsup_t *) ec;
95 break;
96 case XHCI_EC_SUPPORTED_PROTOCOL:
97 psic = XHCI_REG_RD(ec, XHCI_EC_SP_PSIC);
98 major = XHCI_REG_RD(ec, XHCI_EC_SP_MAJOR);
99 minor = XHCI_REG_RD(ec, XHCI_EC_SP_MINOR);
100 name.packed = host2uint32_t_le(XHCI_REG_RD(ec, XHCI_EC_SP_NAME));
101
102 if (name.packed != xhci_name_usb.packed) {
103 /**
104 * The detection of such protocol would work,
105 * but the rest of the implementation is made
106 * for the USB protocol only.
107 */
108 usb_log_error("Unknown protocol %.4s.", name.str);
109 return ENOTSUP;
110 }
111
112 unsigned offset = XHCI_REG_RD(ec, XHCI_EC_SP_CP_OFF);
113 unsigned count = XHCI_REG_RD(ec, XHCI_EC_SP_CP_COUNT);
114 xhci_rh_set_ports_protocol(&hc->rh, offset, count, major);
115
116 // "Implied" speed
117 if (psic == 0) {
118 assert(minor == 0);
119
120 if (major == 2) {
121 speeds[1] = default_psiv_to_port_speed[1];
122 speeds[2] = default_psiv_to_port_speed[2];
123 speeds[3] = default_psiv_to_port_speed[3];
124 } else if (major == 3) {
125 speeds[4] = default_psiv_to_port_speed[4];
126 } else {
127 return EINVAL;
128 }
129
130 usb_log_debug2("Implied speed of USB %u.0 set up.", major);
131 } else {
132 for (unsigned i = 0; i < psic; i++) {
133 xhci_psi_t *psi = xhci_extcap_psi(ec, i);
134 unsigned sim = XHCI_REG_RD(psi, XHCI_PSI_PSIM);
135 unsigned psiv = XHCI_REG_RD(psi, XHCI_PSI_PSIV);
136 unsigned psie = XHCI_REG_RD(psi, XHCI_PSI_PSIE);
137 unsigned psim = XHCI_REG_RD(psi, XHCI_PSI_PSIM);
138 uint64_t bps = PSI_TO_BPS(psie, psim);
139
140 /*
141 * Speed is not implied, but using one of default PSIV. This is
142 * not clearly stated in xHCI spec. There is a clear intention
143 * to allow xHCI to specify its own speed parameters, but
144 * throughout the document, they used fixed values for e.g.
145 * High-speed (3), without stating the controller shall have
146 * implied default speeds - and for instance Intel controllers
147 * do not. So let's check if the values match and if so, accept
148 * the implied USB speed too.
149 *
150 * The main reason we need this is the usb_speed to have
151 * mapping also for devices connected to hubs.
152 */
153 if (psiv < ARRAY_SIZE(default_psiv_to_port_speed)
154 && default_psiv_to_port_speed[psiv].major == major
155 && default_psiv_to_port_speed[psiv].minor == minor
156 && default_psiv_to_port_speed[psiv].rx_bps == bps
157 && default_psiv_to_port_speed[psiv].tx_bps == bps) {
158 speeds[psiv] = default_psiv_to_port_speed[psiv];
159 usb_log_debug2("Assumed default %s speed of USB %u.", usb_str_speed(speeds[psiv].usb_speed), major);
160 continue;
161 }
162
163 // Custom speed
164 speeds[psiv].major = major;
165 speeds[psiv].minor = minor;
166 str_ncpy(speeds[psiv].name, 4, name.str, 4);
167 speeds[psiv].usb_speed = USB_SPEED_MAX;
168
169 if (sim == XHCI_PSI_PLT_SYMM || sim == XHCI_PSI_PLT_RX)
170 speeds[psiv].rx_bps = bps;
171 if (sim == XHCI_PSI_PLT_SYMM || sim == XHCI_PSI_PLT_TX) {
172 speeds[psiv].tx_bps = bps;
173 usb_log_debug2("Speed %u set up for bps %" PRIu64 " / %" PRIu64 ".", psiv, speeds[psiv].rx_bps, speeds[psiv].tx_bps);
174 }
175 }
176 }
177 }
178 }
179 return EOK;
180}
181
182/**
183 * Initialize MMIO spaces of xHC.
184 */
185int hc_init_mmio(xhci_hc_t *hc, const hw_res_list_parsed_t *hw_res)
186{
187 int err;
188
189 if (hw_res->mem_ranges.count != 1) {
190 usb_log_error("Unexpected MMIO area, bailing out.");
191 return EINVAL;
192 }
193
194 hc->mmio_range = hw_res->mem_ranges.ranges[0];
195
196 usb_log_debug("MMIO area at %p (size %zu), IRQ %d.",
197 RNGABSPTR(hc->mmio_range), RNGSZ(hc->mmio_range), hw_res->irqs.irqs[0]);
198
199 if (RNGSZ(hc->mmio_range) < sizeof(xhci_cap_regs_t))
200 return EOVERFLOW;
201
202 void *base;
203 if ((err = pio_enable_range(&hc->mmio_range, &base)))
204 return err;
205
206 hc->reg_base = base;
207 hc->cap_regs = (xhci_cap_regs_t *) base;
208 hc->op_regs = (xhci_op_regs_t *) (base + XHCI_REG_RD(hc->cap_regs, XHCI_CAP_LENGTH));
209 hc->rt_regs = (xhci_rt_regs_t *) (base + XHCI_REG_RD(hc->cap_regs, XHCI_CAP_RTSOFF));
210 hc->db_arry = (xhci_doorbell_t *) (base + XHCI_REG_RD(hc->cap_regs, XHCI_CAP_DBOFF));
211
212 uintptr_t xec_offset = XHCI_REG_RD(hc->cap_regs, XHCI_CAP_XECP) * sizeof(xhci_dword_t);
213 if (xec_offset > 0)
214 hc->xecp = (xhci_extcap_t *) (base + xec_offset);
215
216 usb_log_debug2("Initialized MMIO reg areas:");
217 usb_log_debug2("\tCapability regs: %p", hc->cap_regs);
218 usb_log_debug2("\tOperational regs: %p", hc->op_regs);
219 usb_log_debug2("\tRuntime regs: %p", hc->rt_regs);
220 usb_log_debug2("\tDoorbell array base: %p", hc->db_arry);
221
222 xhci_dump_cap_regs(hc->cap_regs);
223
224 hc->ac64 = XHCI_REG_RD(hc->cap_regs, XHCI_CAP_AC64);
225 hc->max_slots = XHCI_REG_RD(hc->cap_regs, XHCI_CAP_MAX_SLOTS);
226
227 struct timeval tv;
228 getuptime(&tv);
229 hc->wrap_time = tv.tv_sec * 1000000 + tv.tv_usec;
230 hc->wrap_count = 0;
231
232 unsigned ist = XHCI_REG_RD(hc->cap_regs, XHCI_CAP_IST);
233 hc->ist = (ist & 0x10 >> 1) * (ist & 0xf);
234
235 if ((err = xhci_rh_init(&hc->rh, hc)))
236 goto err_pio;
237
238 if ((err = hc_parse_ec(hc)))
239 goto err_rh;
240
241 return EOK;
242
243err_rh:
244 xhci_rh_fini(&hc->rh);
245err_pio:
246 pio_disable(hc->reg_base, RNGSZ(hc->mmio_range));
247 return err;
248}
249
250static int event_worker(void *arg);
251
252/**
253 * Initialize structures kept in allocated memory.
254 */
255int hc_init_memory(xhci_hc_t *hc, ddf_dev_t *device)
256{
257 int err;
258
259 if (dma_buffer_alloc(&hc->dcbaa_dma, (1 + hc->max_slots) * sizeof(uint64_t)))
260 return ENOMEM;
261 hc->dcbaa = hc->dcbaa_dma.virt;
262
263 if ((err = xhci_event_ring_init(&hc->event_ring)))
264 goto err_dcbaa;
265
266 if ((err = xhci_scratchpad_alloc(hc)))
267 goto err_event_ring;
268
269 if ((err = xhci_init_commands(hc)))
270 goto err_scratch;
271
272 if ((err = xhci_bus_init(&hc->bus, hc)))
273 goto err_cmd;
274
275 fid_t fid = fibril_create(&event_worker, hc);
276 if (!fid)
277 goto err_bus;
278
279 // TODO: completion_reset
280 hc->event_fibril_completion.active = true;
281 fibril_mutex_initialize(&hc->event_fibril_completion.guard);
282 fibril_condvar_initialize(&hc->event_fibril_completion.cv);
283
284 xhci_sw_ring_init(&hc->sw_ring, PAGE_SIZE / sizeof(xhci_trb_t));
285
286 fibril_add_ready(fid);
287
288 return EOK;
289
290err_bus:
291 xhci_bus_fini(&hc->bus);
292err_cmd:
293 xhci_fini_commands(hc);
294err_scratch:
295 xhci_scratchpad_free(hc);
296err_event_ring:
297 xhci_event_ring_fini(&hc->event_ring);
298err_dcbaa:
299 hc->dcbaa = NULL;
300 dma_buffer_free(&hc->dcbaa_dma);
301 return err;
302}
303
304/*
305 * Pseudocode:
306 * ip = read(intr[0].iman)
307 * if (ip) {
308 * status = read(usbsts)
309 * assert status
310 * assert ip
311 * accept (passing status)
312 * }
313 * decline
314 */
315static const irq_cmd_t irq_commands[] = {
316 {
317 .cmd = CMD_PIO_READ_32,
318 .dstarg = 3,
319 .addr = NULL /* intr[0].iman */
320 },
321 {
322 .cmd = CMD_AND,
323 .srcarg = 3,
324 .dstarg = 4,
325 .value = 0 /* host2xhci(32, 1) */
326 },
327 {
328 .cmd = CMD_PREDICATE,
329 .srcarg = 4,
330 .value = 5
331 },
332 {
333 .cmd = CMD_PIO_READ_32,
334 .dstarg = 1,
335 .addr = NULL /* usbsts */
336 },
337 {
338 .cmd = CMD_AND,
339 .srcarg = 1,
340 .dstarg = 2,
341 .value = 0 /* host2xhci(32, XHCI_STATUS_ACK_MASK) */
342 },
343 {
344 .cmd = CMD_PIO_WRITE_A_32,
345 .srcarg = 2,
346 .addr = NULL /* usbsts */
347 },
348 {
349 .cmd = CMD_PIO_WRITE_A_32,
350 .srcarg = 3,
351 .addr = NULL /* intr[0].iman */
352 },
353 {
354 .cmd = CMD_ACCEPT
355 },
356 {
357 .cmd = CMD_DECLINE
358 }
359};
360
361
362/**
363 * Generates code to accept interrupts. The xHCI is designed primarily for
364 * MSI/MSI-X, but we use PCI Interrupt Pin. In this mode, all the Interrupters
365 * (except 0) are disabled.
366 */
367int hc_irq_code_gen(irq_code_t *code, xhci_hc_t *hc, const hw_res_list_parsed_t *hw_res)
368{
369 assert(code);
370 assert(hw_res);
371
372 if (hw_res->irqs.count != 1) {
373 usb_log_info("Unexpected HW resources to enable interrupts.");
374 return EINVAL;
375 }
376
377 code->ranges = malloc(sizeof(irq_pio_range_t));
378 if (code->ranges == NULL)
379 return ENOMEM;
380
381 code->cmds = malloc(sizeof(irq_commands));
382 if (code->cmds == NULL) {
383 free(code->ranges);
384 return ENOMEM;
385 }
386
387 code->rangecount = 1;
388 code->ranges[0] = (irq_pio_range_t) {
389 .base = RNGABS(hc->mmio_range),
390 .size = RNGSZ(hc->mmio_range),
391 };
392
393 code->cmdcount = ARRAY_SIZE(irq_commands);
394 memcpy(code->cmds, irq_commands, sizeof(irq_commands));
395
396 void *intr0_iman = RNGABSPTR(hc->mmio_range) + XHCI_REG_RD(hc->cap_regs, XHCI_CAP_RTSOFF) + offsetof(xhci_rt_regs_t, ir[0]);
397 void *usbsts = RNGABSPTR(hc->mmio_range) + XHCI_REG_RD(hc->cap_regs, XHCI_CAP_LENGTH) + offsetof(xhci_op_regs_t, usbsts);
398 code->cmds[0].addr = intr0_iman;
399 code->cmds[1].value = host2xhci(32, 1);
400 code->cmds[3].addr = usbsts;
401 code->cmds[4].value = host2xhci(32, XHCI_STATUS_ACK_MASK);
402 code->cmds[5].addr = usbsts;
403 code->cmds[6].addr = intr0_iman;
404
405 return hw_res->irqs.irqs[0];
406}
407
408/**
409 * Claim xHC from BIOS. Implements handoff as per Section 4.22.1 of xHCI spec.
410 */
411int hc_claim(xhci_hc_t *hc, ddf_dev_t *dev)
412{
413 /* No legacy support capability, the controller is solely for us */
414 if (!hc->legsup)
415 return EOK;
416
417 if (xhci_reg_wait(&hc->op_regs->usbsts, XHCI_REG_MASK(XHCI_OP_CNR), 0))
418 return ETIMEOUT;
419
420 usb_log_debug2("LEGSUP: bios: %x, os: %x", hc->legsup->sem_bios, hc->legsup->sem_os);
421 XHCI_REG_SET(hc->legsup, XHCI_LEGSUP_SEM_OS, 1);
422 for (int i = 0; i <= (XHCI_LEGSUP_BIOS_TIMEOUT_US / XHCI_LEGSUP_POLLING_DELAY_1MS); i++) {
423 usb_log_debug2("LEGSUP: elapsed: %i ms, bios: %x, os: %x", i,
424 XHCI_REG_RD(hc->legsup, XHCI_LEGSUP_SEM_BIOS),
425 XHCI_REG_RD(hc->legsup, XHCI_LEGSUP_SEM_OS));
426 if (XHCI_REG_RD(hc->legsup, XHCI_LEGSUP_SEM_BIOS) == 0) {
427 return XHCI_REG_RD(hc->legsup, XHCI_LEGSUP_SEM_OS) == 1 ? EOK : EIO;
428 }
429 async_usleep(XHCI_LEGSUP_POLLING_DELAY_1MS);
430 }
431 usb_log_error("BIOS did not release XHCI legacy hold!");
432
433 return ENOTSUP;
434}
435
436/**
437 * Ask the xHC to reset its state. Implements sequence
438 */
439static int hc_reset(xhci_hc_t *hc)
440{
441 if (xhci_reg_wait(&hc->op_regs->usbsts, XHCI_REG_MASK(XHCI_OP_CNR), 0))
442 return ETIMEOUT;
443
444 /* Stop the HC: set R/S to 0 */
445 XHCI_REG_CLR(hc->op_regs, XHCI_OP_RS, 1);
446
447 /* Wait until the HC is halted - it shall take at most 16 ms */
448 if (xhci_reg_wait(&hc->op_regs->usbsts, XHCI_REG_MASK(XHCI_OP_HCH), XHCI_REG_MASK(XHCI_OP_HCH)))
449 return ETIMEOUT;
450
451 /* Reset */
452 XHCI_REG_SET(hc->op_regs, XHCI_OP_HCRST, 1);
453
454 /* Wait until the reset is complete */
455 if (xhci_reg_wait(&hc->op_regs->usbcmd, XHCI_REG_MASK(XHCI_OP_HCRST), 0))
456 return ETIMEOUT;
457
458 return EOK;
459}
460
461/**
462 * Initialize the HC: section 4.2
463 */
464int hc_start(xhci_hc_t *hc, bool irq)
465{
466 int err;
467
468 if ((err = hc_reset(hc)))
469 return err;
470
471 if (xhci_reg_wait(&hc->op_regs->usbsts, XHCI_REG_MASK(XHCI_OP_CNR), 0))
472 return ETIMEOUT;
473
474 uint64_t dcbaaptr = hc->dcbaa_dma.phys;
475 XHCI_REG_WR(hc->op_regs, XHCI_OP_DCBAAP_LO, LOWER32(dcbaaptr));
476 XHCI_REG_WR(hc->op_regs, XHCI_OP_DCBAAP_HI, UPPER32(dcbaaptr));
477 XHCI_REG_WR(hc->op_regs, XHCI_OP_MAX_SLOTS_EN, hc->max_slots);
478
479 uint64_t crcr = xhci_trb_ring_get_dequeue_ptr(&hc->cr.trb_ring);
480 if (hc->cr.trb_ring.pcs)
481 crcr |= XHCI_REG_MASK(XHCI_OP_RCS);
482 XHCI_REG_WR(hc->op_regs, XHCI_OP_CRCR_LO, LOWER32(crcr));
483 XHCI_REG_WR(hc->op_regs, XHCI_OP_CRCR_HI, UPPER32(crcr));
484
485 XHCI_REG_SET(hc->op_regs, XHCI_OP_EWE, 1);
486
487 xhci_interrupter_regs_t *intr0 = &hc->rt_regs->ir[0];
488 XHCI_REG_WR(intr0, XHCI_INTR_ERSTSZ, hc->event_ring.segment_count);
489 uint64_t erdp = hc->event_ring.dequeue_ptr;
490 XHCI_REG_WR(intr0, XHCI_INTR_ERDP_LO, LOWER32(erdp));
491 XHCI_REG_WR(intr0, XHCI_INTR_ERDP_HI, UPPER32(erdp));
492 uint64_t erstptr = hc->event_ring.erst.phys;
493 XHCI_REG_WR(intr0, XHCI_INTR_ERSTBA_LO, LOWER32(erstptr));
494 XHCI_REG_WR(intr0, XHCI_INTR_ERSTBA_HI, UPPER32(erstptr));
495
496
497 if (irq) {
498 XHCI_REG_SET(intr0, XHCI_INTR_IE, 1);
499 XHCI_REG_SET(hc->op_regs, XHCI_OP_INTE, 1);
500 }
501
502 XHCI_REG_SET(hc->op_regs, XHCI_OP_HSEE, 1);
503
504 XHCI_REG_SET(hc->op_regs, XHCI_OP_RS, 1);
505
506 /* The reset changed status of all ports, and SW originated reason does
507 * not cause an interrupt.
508 */
509 for (uint8_t port = 1; port <= hc->rh.max_ports; ++port)
510 xhci_rh_handle_port_change(&hc->rh, port);
511
512 return EOK;
513}
514
515/**
516 * Used only when polling. Shall supplement the irq_commands.
517 */
518int hc_status(bus_t *bus, uint32_t *status)
519{
520 xhci_hc_t *hc = bus_to_hc(bus);
521 int ip = XHCI_REG_RD(hc->rt_regs->ir, XHCI_INTR_IP);
522 if (ip) {
523 *status = XHCI_REG_RD(hc->op_regs, XHCI_OP_STATUS);
524 XHCI_REG_WR(hc->op_regs, XHCI_OP_STATUS, *status & XHCI_STATUS_ACK_MASK);
525 XHCI_REG_WR(hc->rt_regs->ir, XHCI_INTR_IP, 1);
526
527 /* interrupt handler expects status from irq_commands, which is
528 * in xhci order. */
529 *status = host2xhci(32, *status);
530 }
531
532 usb_log_debug2("Polled status: %x", *status);
533 return EOK;
534}
535
536static int xhci_handle_mfindex_wrap_event(xhci_hc_t *hc, xhci_trb_t *trb)
537{
538 struct timeval tv;
539 getuptime(&tv);
540 usb_log_debug2("Microframe index wrapped (@%lu.%li, %"PRIu64" total).", tv.tv_sec, tv.tv_usec, hc->wrap_count);
541 hc->wrap_time = ((uint64_t) tv.tv_sec) * 1000000 + ((uint64_t) tv.tv_usec);
542 ++hc->wrap_count;
543 return EOK;
544}
545
546static int handle_port_status_change_event(xhci_hc_t *hc, xhci_trb_t *trb)
547{
548 uint8_t port_id = XHCI_QWORD_EXTRACT(trb->parameter, 31, 24);
549 usb_log_debug("Port status change event detected for port %u.", port_id);
550 xhci_rh_handle_port_change(&hc->rh, port_id);
551 return EOK;
552}
553
554typedef int (*event_handler) (xhci_hc_t *, xhci_trb_t *trb);
555
556/**
557 * These events are handled by separate event handling fibril.
558 */
559static event_handler event_handlers [] = {
560 [XHCI_TRB_TYPE_PORT_STATUS_CHANGE_EVENT] = &handle_port_status_change_event,
561 [XHCI_TRB_TYPE_TRANSFER_EVENT] = &xhci_handle_transfer_event,
562};
563
564/**
565 * These events are handled directly in the interrupt handler, thus they must
566 * not block waiting for another interrupt.
567 */
568static event_handler event_handlers_fast [] = {
569 [XHCI_TRB_TYPE_COMMAND_COMPLETION_EVENT] = &xhci_handle_command_completion,
570 [XHCI_TRB_TYPE_MFINDEX_WRAP_EVENT] = &xhci_handle_mfindex_wrap_event,
571};
572
573static int hc_handle_event(xhci_hc_t *hc, xhci_trb_t *trb)
574{
575 const unsigned type = TRB_TYPE(*trb);
576
577 if (type <= ARRAY_SIZE(event_handlers_fast) && event_handlers_fast[type])
578 return event_handlers_fast[type](hc, trb);
579
580 if (type <= ARRAY_SIZE(event_handlers) && event_handlers[type])
581 return xhci_sw_ring_enqueue(&hc->sw_ring, trb);
582
583 return ENOTSUP;
584}
585
586static int event_worker(void *arg)
587{
588 int err;
589 xhci_trb_t trb;
590 xhci_hc_t * const hc = arg;
591 assert(hc);
592
593 while (xhci_sw_ring_dequeue(&hc->sw_ring, &trb) != EINTR) {
594 const unsigned type = TRB_TYPE(trb);
595
596 if ((err = event_handlers[type](hc, &trb)))
597 usb_log_error("Failed to handle event: %s", str_error(err));
598 }
599
600 // TODO: completion_complete
601 fibril_mutex_lock(&hc->event_fibril_completion.guard);
602 hc->event_fibril_completion.active = false;
603 fibril_condvar_wait(&hc->event_fibril_completion.cv, &hc->event_fibril_completion.guard);
604 fibril_mutex_unlock(&hc->event_fibril_completion.guard);
605
606 return EOK;
607}
608
609/**
610 * Dequeue from event ring and handle dequeued events.
611 *
612 * As there can be events, that blocks on waiting for subsequent events,
613 * we solve this problem by first copying the event TRBs from the event ring,
614 * then asserting EHB and only after, handling the events.
615 *
616 * Whenever the event handling blocks, it switches fibril, and incoming
617 * IPC notification will create new event handling fibril for us.
618 */
619static void hc_run_event_ring(xhci_hc_t *hc, xhci_event_ring_t *event_ring, xhci_interrupter_regs_t *intr)
620{
621 int err;
622
623 xhci_trb_t trb;
624 hc->event_handler = fibril_get_id();
625
626 while ((err = xhci_event_ring_dequeue(event_ring, &trb)) != ENOENT) {
627 if ((err = hc_handle_event(hc, &trb)) != EOK) {
628 usb_log_error("Failed to handle event in interrupt: %s", str_error(err));
629 }
630
631 uint64_t erdp = hc->event_ring.dequeue_ptr;
632 XHCI_REG_WR(intr, XHCI_INTR_ERDP_LO, LOWER32(erdp));
633 XHCI_REG_WR(intr, XHCI_INTR_ERDP_HI, UPPER32(erdp));
634 }
635
636 hc->event_handler = 0;
637
638 /* Update the ERDP to make room in the ring. */
639 uint64_t erdp = hc->event_ring.dequeue_ptr;
640 erdp |= XHCI_REG_MASK(XHCI_INTR_ERDP_EHB);
641 XHCI_REG_WR(intr, XHCI_INTR_ERDP_LO, LOWER32(erdp));
642 XHCI_REG_WR(intr, XHCI_INTR_ERDP_HI, UPPER32(erdp));
643
644 usb_log_debug2("Event ring run finished.");
645}
646
647/**
648 * Handle an interrupt request from xHC. Resolve all situations that trigger an
649 * interrupt separately.
650 *
651 * Note that all RW1C bits in USBSTS register are cleared at the time of
652 * handling the interrupt in irq_code. This method is the top-half.
653 *
654 * @param status contents of USBSTS register at the time of the interrupt.
655 */
656void hc_interrupt(bus_t *bus, uint32_t status)
657{
658 xhci_hc_t *hc = bus_to_hc(bus);
659 status = xhci2host(32, status);
660
661 if (status & XHCI_REG_MASK(XHCI_OP_HSE)) {
662 usb_log_error("Host controller error occured. Bad things gonna happen...");
663 status &= ~XHCI_REG_MASK(XHCI_OP_HSE);
664 }
665
666 if (status & XHCI_REG_MASK(XHCI_OP_EINT)) {
667 usb_log_debug2("Event interrupt, running the event ring.");
668 hc_run_event_ring(hc, &hc->event_ring, &hc->rt_regs->ir[0]);
669 status &= ~XHCI_REG_MASK(XHCI_OP_EINT);
670 }
671
672 if (status & XHCI_REG_MASK(XHCI_OP_SRE)) {
673 usb_log_error("Save/Restore error occured. WTF, S/R mechanism not implemented!");
674 status &= ~XHCI_REG_MASK(XHCI_OP_SRE);
675 }
676
677 /* According to Note on p. 302, we may safely ignore the PCD bit. */
678 status &= ~XHCI_REG_MASK(XHCI_OP_PCD);
679
680 if (status) {
681 usb_log_error("Non-zero status after interrupt handling (%08x) - missing something?", status);
682 }
683}
684
685/**
686 * Tear down all in-memory structures.
687 */
688void hc_fini(xhci_hc_t *hc)
689{
690 xhci_sw_ring_stop(&hc->sw_ring);
691
692 // TODO: completion_wait
693 fibril_mutex_lock(&hc->event_fibril_completion.guard);
694 while (hc->event_fibril_completion.active)
695 fibril_condvar_wait(&hc->event_fibril_completion.cv, &hc->event_fibril_completion.guard);
696 fibril_mutex_unlock(&hc->event_fibril_completion.guard);
697 xhci_sw_ring_fini(&hc->sw_ring);
698
699 xhci_bus_fini(&hc->bus);
700 xhci_event_ring_fini(&hc->event_ring);
701 xhci_scratchpad_free(hc);
702 dma_buffer_free(&hc->dcbaa_dma);
703 xhci_fini_commands(hc);
704 xhci_rh_fini(&hc->rh);
705 pio_disable(hc->reg_base, RNGSZ(hc->mmio_range));
706 usb_log_info("Finalized.");
707}
708
709/**
710 * Ring a xHC Doorbell. Implements section 4.7.
711 */
712void hc_ring_doorbell(xhci_hc_t *hc, unsigned doorbell, unsigned target)
713{
714 assert(hc);
715 uint32_t v = host2xhci(32, target & BIT_RRANGE(uint32_t, 7));
716 pio_write_32(&hc->db_arry[doorbell], v);
717 usb_log_debug2("Ringing doorbell %d (target: %d)", doorbell, target);
718}
719
720/**
721 * Issue an Enable Slot command, returning the obtained Slot ID.
722 *
723 * @param slot_id Pointer where to store the obtained Slot ID.
724 */
725int hc_enable_slot(xhci_hc_t *hc, uint32_t *slot_id)
726{
727 assert(hc);
728
729 int err;
730 xhci_cmd_t cmd;
731 xhci_cmd_init(&cmd, XHCI_CMD_ENABLE_SLOT);
732
733 if ((err = xhci_cmd_sync(hc, &cmd))) {
734 goto end;
735 }
736
737 if (slot_id) {
738 *slot_id = cmd.slot_id;
739 }
740
741end:
742 xhci_cmd_fini(&cmd);
743 return err;
744}
745
746/**
747 * Issue a Disable Slot command for a slot occupied by device.
748 *
749 * Frees the device context
750 */
751int hc_disable_slot(xhci_hc_t *hc, xhci_device_t *dev)
752{
753 int err;
754 assert(hc);
755
756 if ((err = xhci_cmd_sync_inline(hc, DISABLE_SLOT, .slot_id = dev->slot_id))) {
757 return err;
758 }
759
760 /* Free the device context. */
761 hc->dcbaa[dev->slot_id] = 0;
762 dma_buffer_free(&dev->dev_ctx);
763
764 /* Mark the slot as invalid. */
765 dev->slot_id = 0;
766
767 return EOK;
768}
769
770/**
771 * Prepare an empty Endpoint Input Context inside a dma buffer.
772 */
773static int create_configure_ep_input_ctx(dma_buffer_t *dma_buf)
774{
775 const int err = dma_buffer_alloc(dma_buf, sizeof(xhci_input_ctx_t));
776 if (err)
777 return err;
778
779 xhci_input_ctx_t *ictx = dma_buf->virt;
780 memset(ictx, 0, sizeof(xhci_input_ctx_t));
781
782 // Quoting sec. 4.6.5 and 4.6.6: A1, D0, D1 are down (already zeroed), A0 is up.
783 XHCI_INPUT_CTRL_CTX_ADD_SET(ictx->ctrl_ctx, 0);
784
785 // As we always allocate space for whole input context, we can set this to maximum
786 XHCI_SLOT_CTX_ENTRIES_SET(ictx->slot_ctx, 31);
787
788 return EOK;
789}
790
791/**
792 * Initialize a device, assigning it an address. Implements section 4.3.4.
793 *
794 * @param dev Device to assing an address (unconfigured yet)
795 * @param ep0 EP0 of device TODO remove, can be fetched from dev
796 */
797int hc_address_device(xhci_hc_t *hc, xhci_device_t *dev, xhci_endpoint_t *ep0)
798{
799 int err = ENOMEM;
800
801 /* Although we have the precise PSIV value on devices of tier 1,
802 * we have to rely on reverse mapping on others. */
803 if (!usb_speed_to_psiv[dev->base.speed]) {
804 usb_log_error("Device reported an USB speed (%s) that cannot be mapped to HC port speed.", usb_str_speed(dev->base.speed));
805 return EINVAL;
806 }
807
808 /* Setup and register device context */
809 if (dma_buffer_alloc(&dev->dev_ctx, sizeof(xhci_device_ctx_t)))
810 goto err;
811 memset(dev->dev_ctx.virt, 0, sizeof(xhci_device_ctx_t));
812
813 hc->dcbaa[dev->slot_id] = host2xhci(64, dev->dev_ctx.phys);
814
815 /* Issue configure endpoint command (sec 4.3.5). */
816 dma_buffer_t ictx_dma_buf;
817 if ((err = create_configure_ep_input_ctx(&ictx_dma_buf))) {
818 goto err_dev_ctx;
819 }
820 xhci_input_ctx_t *ictx = ictx_dma_buf.virt;
821
822 /* Initialize slot_ctx according to section 4.3.3 point 3. */
823 XHCI_SLOT_ROOT_HUB_PORT_SET(ictx->slot_ctx, dev->rh_port);
824 XHCI_SLOT_CTX_ENTRIES_SET(ictx->slot_ctx, 1);
825 XHCI_SLOT_ROUTE_STRING_SET(ictx->slot_ctx, dev->route_str);
826 XHCI_SLOT_SPEED_SET(ictx->slot_ctx, usb_speed_to_psiv[dev->base.speed]);
827
828 /* Setup Transaction Translation. TODO: Test this with HS hub. */
829 if (dev->base.tt.dev != NULL) {
830 xhci_device_t *hub = xhci_device_get(dev->base.tt.dev);
831 XHCI_SLOT_TT_HUB_SLOT_ID_SET(ictx->slot_ctx, hub->slot_id);
832 XHCI_SLOT_TT_HUB_PORT_SET(ictx->slot_ctx, dev->base.tt.port);
833 XHCI_SLOT_MTT_SET(ictx->slot_ctx, 0); // MTT not supported yet
834 }
835
836 /* Copy endpoint 0 context and set A1 flag. */
837 XHCI_INPUT_CTRL_CTX_ADD_SET(ictx->ctrl_ctx, 1);
838 xhci_setup_endpoint_context(ep0, &ictx->endpoint_ctx[0]);
839
840 /* Issue Address Device command. */
841 if ((err = xhci_cmd_sync_inline(hc, ADDRESS_DEVICE, .slot_id = dev->slot_id, .input_ctx = ictx_dma_buf))) {
842 goto err_dev_ctx;
843 }
844
845 xhci_device_ctx_t *dev_ctx = dev->dev_ctx.virt;
846 dev->base.address = XHCI_SLOT_DEVICE_ADDRESS(dev_ctx->slot_ctx);
847 usb_log_debug2("Obtained USB address: %d.", dev->base.address);
848
849 return EOK;
850
851err_dev_ctx:
852 hc->dcbaa[dev->slot_id] = 0;
853 dma_buffer_free(&dev->dev_ctx);
854err:
855 return err;
856}
857
858/**
859 * Issue a Configure Device command for a device in slot.
860 *
861 * @param slot_id Slot ID assigned to the device.
862 */
863int hc_configure_device(xhci_hc_t *hc, uint32_t slot_id)
864{
865 /* Issue configure endpoint command (sec 4.3.5). */
866 dma_buffer_t ictx_dma_buf;
867 const int err = create_configure_ep_input_ctx(&ictx_dma_buf);
868 if (err)
869 return err;
870
871 // TODO: Set slot context and other flags. (probably forgot a lot of 'em)
872
873 return xhci_cmd_sync_inline(hc, CONFIGURE_ENDPOINT, .slot_id = slot_id, .input_ctx = ictx_dma_buf);
874}
875
876/**
877 * Issue a Deconfigure Device command for a device in slot.
878 *
879 * @param slot_id Slot ID assigned to the device.
880 */
881int hc_deconfigure_device(xhci_hc_t *hc, uint32_t slot_id)
882{
883 /* Issue configure endpoint command (sec 4.3.5) with the DC flag. */
884 return xhci_cmd_sync_inline(hc, CONFIGURE_ENDPOINT, .slot_id = slot_id, .deconfigure = true);
885}
886
887/**
888 * Instruct xHC to add an endpoint with supplied endpoint context.
889 *
890 * @param slot_id Slot ID assigned to the device.
891 * @param ep_idx Endpoint index (number + direction) in question
892 * @param ep_ctx Endpoint context of the endpoint
893 */
894int hc_add_endpoint(xhci_hc_t *hc, uint32_t slot_id, uint8_t ep_idx, xhci_ep_ctx_t *ep_ctx)
895{
896 /* Issue configure endpoint command (sec 4.3.5). */
897 dma_buffer_t ictx_dma_buf;
898 const int err = create_configure_ep_input_ctx(&ictx_dma_buf);
899 if (err)
900 return err;
901
902 xhci_input_ctx_t *ictx = ictx_dma_buf.virt;
903 XHCI_INPUT_CTRL_CTX_ADD_SET(ictx->ctrl_ctx, ep_idx + 1); /* Preceded by slot ctx */
904 memcpy(&ictx->endpoint_ctx[ep_idx], ep_ctx, sizeof(xhci_ep_ctx_t));
905
906 // TODO: Set slot context and other flags. (probably forgot a lot of 'em)
907
908 return xhci_cmd_sync_inline(hc, CONFIGURE_ENDPOINT, .slot_id = slot_id, .input_ctx = ictx_dma_buf);
909}
910
911/**
912 * Instruct xHC to drop an endpoint.
913 *
914 * @param slot_id Slot ID assigned to the device.
915 * @param ep_idx Endpoint index (number + direction) in question
916 */
917int hc_drop_endpoint(xhci_hc_t *hc, uint32_t slot_id, uint8_t ep_idx)
918{
919 /* Issue configure endpoint command (sec 4.3.5). */
920 dma_buffer_t ictx_dma_buf;
921 const int err = create_configure_ep_input_ctx(&ictx_dma_buf);
922 if (err)
923 return err;
924
925 xhci_input_ctx_t *ictx = ictx_dma_buf.virt;
926 XHCI_INPUT_CTRL_CTX_DROP_SET(ictx->ctrl_ctx, ep_idx + 1); /* Preceded by slot ctx */
927 // TODO: Set slot context and other flags. (probably forgot a lot of 'em)
928
929 return xhci_cmd_sync_inline(hc, CONFIGURE_ENDPOINT, .slot_id = slot_id, .input_ctx = ictx_dma_buf);
930}
931
932/**
933 * Instruct xHC to update information about an endpoint, using supplied
934 * endpoint context.
935 *
936 * @param slot_id Slot ID assigned to the device.
937 * @param ep_idx Endpoint index (number + direction) in question
938 * @param ep_ctx Endpoint context of the endpoint
939 */
940int hc_update_endpoint(xhci_hc_t *hc, uint32_t slot_id, uint8_t ep_idx, xhci_ep_ctx_t *ep_ctx)
941{
942 dma_buffer_t ictx_dma_buf;
943 const int err = dma_buffer_alloc(&ictx_dma_buf, sizeof(xhci_input_ctx_t));
944 if (err)
945 return err;
946
947 xhci_input_ctx_t *ictx = ictx_dma_buf.virt;
948 memset(ictx, 0, sizeof(xhci_input_ctx_t));
949
950 XHCI_INPUT_CTRL_CTX_ADD_SET(ictx->ctrl_ctx, ep_idx + 1);
951 memcpy(&ictx->endpoint_ctx[ep_idx], ep_ctx, sizeof(xhci_ep_ctx_t));
952
953 return xhci_cmd_sync_inline(hc, EVALUATE_CONTEXT, .slot_id = slot_id, .input_ctx = ictx_dma_buf);
954}
955
956/**
957 * Instruct xHC to stop running a transfer ring on an endpoint.
958 *
959 * @param slot_id Slot ID assigned to the device.
960 * @param ep_idx Endpoint index (number + direction) in question
961 */
962int hc_stop_endpoint(xhci_hc_t *hc, uint32_t slot_id, uint8_t ep_idx)
963{
964 return xhci_cmd_sync_inline(hc, STOP_ENDPOINT, .slot_id = slot_id, .endpoint_id = ep_idx);
965}
966
967/**
968 * Instruct xHC to reset halted endpoint.
969 *
970 * @param slot_id Slot ID assigned to the device.
971 * @param ep_idx Endpoint index (number + direction) in question
972 */
973int hc_reset_endpoint(xhci_hc_t *hc, uint32_t slot_id, uint8_t ep_idx)
974{
975 return xhci_cmd_sync_inline(hc, RESET_ENDPOINT, .slot_id = slot_id, .endpoint_id = ep_idx);
976}
977
978/**
979 * @}
980 */
Note: See TracBrowser for help on using the repository browser.