xref: /openbsd-src/sys/dev/usb/xhci.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /* $OpenBSD: xhci.c,v 1.113 2020/03/02 16:30:39 visa Exp $ */
2 
3 /*
4  * Copyright (c) 2014-2015 Martin Pieuchot
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/param.h>
20 #include <sys/systm.h>
21 #include <sys/kernel.h>
22 #include <sys/malloc.h>
23 #include <sys/device.h>
24 #include <sys/queue.h>
25 #include <sys/timeout.h>
26 #include <sys/pool.h>
27 #include <sys/endian.h>
28 #include <sys/rwlock.h>
29 
30 #include <machine/bus.h>
31 
32 #include <dev/usb/usb.h>
33 #include <dev/usb/usbdi.h>
34 #include <dev/usb/usbdivar.h>
35 #include <dev/usb/usb_mem.h>
36 
37 #include <dev/usb/xhcireg.h>
38 #include <dev/usb/xhcivar.h>
39 
40 struct cfdriver xhci_cd = {
41 	NULL, "xhci", DV_DULL
42 };
43 
44 #ifdef XHCI_DEBUG
45 #define DPRINTF(x)	do { if (xhcidebug) printf x; } while(0)
46 #define DPRINTFN(n,x)	do { if (xhcidebug>(n)) printf x; } while (0)
47 int xhcidebug = 3;
48 #else
49 #define DPRINTF(x)
50 #define DPRINTFN(n,x)
51 #endif
52 
53 #define DEVNAME(sc)	((sc)->sc_bus.bdev.dv_xname)
54 
55 #define TRBOFF(r, trb)	((char *)(trb) - (char *)((r)->trbs))
56 #define DEQPTR(r)	((r).dma.paddr + (sizeof(struct xhci_trb) * (r).index))
57 
58 struct pool *xhcixfer;
59 
60 struct xhci_pipe {
61 	struct usbd_pipe	pipe;
62 
63 	uint8_t			dci;
64 	uint8_t			slot;	/* Device slot ID */
65 	struct xhci_ring	ring;
66 
67 	/*
68 	 * XXX used to pass the xfer pointer back to the
69 	 * interrupt routine, better way?
70 	 */
71 	struct usbd_xfer	*pending_xfers[XHCI_MAX_XFER];
72 	struct usbd_xfer	*aborted_xfer;
73 	int			 halted;
74 	size_t			 free_trbs;
75 	int			 skip;
76 };
77 
78 int	xhci_reset(struct xhci_softc *);
79 int	xhci_intr1(struct xhci_softc *);
80 void	xhci_event_dequeue(struct xhci_softc *);
81 void	xhci_event_xfer(struct xhci_softc *, uint64_t, uint32_t, uint32_t);
82 int	xhci_event_xfer_generic(struct xhci_softc *, struct usbd_xfer *,
83 	    struct xhci_pipe *, uint32_t, int, uint8_t, uint8_t, uint8_t);
84 int	xhci_event_xfer_isoc(struct usbd_xfer *, struct xhci_pipe *,
85 	    uint32_t, int);
86 void	xhci_event_command(struct xhci_softc *, uint64_t);
87 void	xhci_event_port_change(struct xhci_softc *, uint64_t, uint32_t);
88 int	xhci_pipe_init(struct xhci_softc *, struct usbd_pipe *);
89 int	xhci_context_setup(struct xhci_softc *, struct usbd_pipe *);
90 int	xhci_scratchpad_alloc(struct xhci_softc *, int);
91 void	xhci_scratchpad_free(struct xhci_softc *);
92 int	xhci_softdev_alloc(struct xhci_softc *, uint8_t);
93 void	xhci_softdev_free(struct xhci_softc *, uint8_t);
94 int	xhci_ring_alloc(struct xhci_softc *, struct xhci_ring *, size_t,
95 	    size_t);
96 void	xhci_ring_free(struct xhci_softc *, struct xhci_ring *);
97 void	xhci_ring_reset(struct xhci_softc *, struct xhci_ring *);
98 struct	xhci_trb *xhci_ring_consume(struct xhci_softc *, struct xhci_ring *);
99 struct	xhci_trb *xhci_ring_produce(struct xhci_softc *, struct xhci_ring *);
100 
101 struct	xhci_trb *xhci_xfer_get_trb(struct xhci_softc *, struct usbd_xfer*,
102 	    uint8_t *, int);
103 void	xhci_xfer_done(struct usbd_xfer *xfer);
104 /* xHCI command helpers. */
105 int	xhci_command_submit(struct xhci_softc *, struct xhci_trb *, int);
106 int	xhci_command_abort(struct xhci_softc *);
107 
108 void	xhci_cmd_reset_ep_async(struct xhci_softc *, uint8_t, uint8_t);
109 void	xhci_cmd_set_tr_deq_async(struct xhci_softc *, uint8_t, uint8_t, uint64_t);
110 int	xhci_cmd_configure_ep(struct xhci_softc *, uint8_t, uint64_t);
111 int	xhci_cmd_stop_ep(struct xhci_softc *, uint8_t, uint8_t);
112 int	xhci_cmd_slot_control(struct xhci_softc *, uint8_t *, int);
113 int	xhci_cmd_set_address(struct xhci_softc *, uint8_t,  uint64_t, uint32_t);
114 int	xhci_cmd_evaluate_ctx(struct xhci_softc *, uint8_t, uint64_t);
115 #ifdef XHCI_DEBUG
116 int	xhci_cmd_noop(struct xhci_softc *);
117 #endif
118 
119 /* XXX should be part of the Bus interface. */
120 void	xhci_abort_xfer(struct usbd_xfer *, usbd_status);
121 void	xhci_pipe_close(struct usbd_pipe *);
122 void	xhci_noop(struct usbd_xfer *);
123 
124 void 	xhci_timeout(void *);
125 void	xhci_timeout_task(void *);
126 
127 /* USBD Bus Interface. */
128 usbd_status	  xhci_pipe_open(struct usbd_pipe *);
129 int		  xhci_setaddr(struct usbd_device *, int);
130 void		  xhci_softintr(void *);
131 void		  xhci_poll(struct usbd_bus *);
132 struct usbd_xfer *xhci_allocx(struct usbd_bus *);
133 void		  xhci_freex(struct usbd_bus *, struct usbd_xfer *);
134 
135 usbd_status	  xhci_root_ctrl_transfer(struct usbd_xfer *);
136 usbd_status	  xhci_root_ctrl_start(struct usbd_xfer *);
137 
138 usbd_status	  xhci_root_intr_transfer(struct usbd_xfer *);
139 usbd_status	  xhci_root_intr_start(struct usbd_xfer *);
140 void		  xhci_root_intr_abort(struct usbd_xfer *);
141 void		  xhci_root_intr_done(struct usbd_xfer *);
142 
143 usbd_status	  xhci_device_ctrl_transfer(struct usbd_xfer *);
144 usbd_status	  xhci_device_ctrl_start(struct usbd_xfer *);
145 void		  xhci_device_ctrl_abort(struct usbd_xfer *);
146 
147 usbd_status	  xhci_device_generic_transfer(struct usbd_xfer *);
148 usbd_status	  xhci_device_generic_start(struct usbd_xfer *);
149 void		  xhci_device_generic_abort(struct usbd_xfer *);
150 void		  xhci_device_generic_done(struct usbd_xfer *);
151 
152 usbd_status	  xhci_device_isoc_transfer(struct usbd_xfer *);
153 usbd_status	  xhci_device_isoc_start(struct usbd_xfer *);
154 
155 #define XHCI_INTR_ENDPT 1
156 
157 struct usbd_bus_methods xhci_bus_methods = {
158 	.open_pipe = xhci_pipe_open,
159 	.dev_setaddr = xhci_setaddr,
160 	.soft_intr = xhci_softintr,
161 	.do_poll = xhci_poll,
162 	.allocx = xhci_allocx,
163 	.freex = xhci_freex,
164 };
165 
166 struct usbd_pipe_methods xhci_root_ctrl_methods = {
167 	.transfer = xhci_root_ctrl_transfer,
168 	.start = xhci_root_ctrl_start,
169 	.abort = xhci_noop,
170 	.close = xhci_pipe_close,
171 	.done = xhci_noop,
172 };
173 
174 struct usbd_pipe_methods xhci_root_intr_methods = {
175 	.transfer = xhci_root_intr_transfer,
176 	.start = xhci_root_intr_start,
177 	.abort = xhci_root_intr_abort,
178 	.close = xhci_pipe_close,
179 	.done = xhci_root_intr_done,
180 };
181 
182 struct usbd_pipe_methods xhci_device_ctrl_methods = {
183 	.transfer = xhci_device_ctrl_transfer,
184 	.start = xhci_device_ctrl_start,
185 	.abort = xhci_device_ctrl_abort,
186 	.close = xhci_pipe_close,
187 	.done = xhci_noop,
188 };
189 
190 struct usbd_pipe_methods xhci_device_intr_methods = {
191 	.transfer = xhci_device_generic_transfer,
192 	.start = xhci_device_generic_start,
193 	.abort = xhci_device_generic_abort,
194 	.close = xhci_pipe_close,
195 	.done = xhci_device_generic_done,
196 };
197 
198 struct usbd_pipe_methods xhci_device_bulk_methods = {
199 	.transfer = xhci_device_generic_transfer,
200 	.start = xhci_device_generic_start,
201 	.abort = xhci_device_generic_abort,
202 	.close = xhci_pipe_close,
203 	.done = xhci_device_generic_done,
204 };
205 
206 struct usbd_pipe_methods xhci_device_isoc_methods = {
207 	.transfer = xhci_device_isoc_transfer,
208 	.start = xhci_device_isoc_start,
209 	.abort = xhci_device_generic_abort,
210 	.close = xhci_pipe_close,
211 	.done = xhci_noop,
212 };
213 
214 #ifdef XHCI_DEBUG
215 static void
216 xhci_dump_trb(struct xhci_trb *trb)
217 {
218 	printf("trb=%p (0x%016llx 0x%08x 0x%b)\n", trb,
219 	    (long long)letoh64(trb->trb_paddr), letoh32(trb->trb_status),
220 	    (int)letoh32(trb->trb_flags), XHCI_TRB_FLAGS_BITMASK);
221 }
222 #endif
223 
224 int	usbd_dma_contig_alloc(struct usbd_bus *, struct usbd_dma_info *,
225 	    void **, bus_size_t, bus_size_t, bus_size_t);
226 void	usbd_dma_contig_free(struct usbd_bus *, struct usbd_dma_info *);
227 
228 int
229 usbd_dma_contig_alloc(struct usbd_bus *bus, struct usbd_dma_info *dma,
230     void **kvap, bus_size_t size, bus_size_t alignment, bus_size_t boundary)
231 {
232 	int error;
233 
234 	dma->tag = bus->dmatag;
235 	dma->size = size;
236 
237 	error = bus_dmamap_create(dma->tag, size, 1, size, boundary,
238 	    BUS_DMA_NOWAIT, &dma->map);
239 	if (error != 0)
240 		return (error);
241 
242 	error = bus_dmamem_alloc(dma->tag, size, alignment, boundary, &dma->seg,
243 	    1, &dma->nsegs, BUS_DMA_NOWAIT | BUS_DMA_ZERO);
244 	if (error != 0)
245 		goto destroy;
246 
247 	error = bus_dmamem_map(dma->tag, &dma->seg, 1, size, &dma->vaddr,
248 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT);
249 	if (error != 0)
250 		goto free;
251 
252 	error = bus_dmamap_load_raw(dma->tag, dma->map, &dma->seg, 1, size,
253 	    BUS_DMA_NOWAIT);
254 	if (error != 0)
255 		goto unmap;
256 
257 	bus_dmamap_sync(dma->tag, dma->map, 0, size, BUS_DMASYNC_PREREAD |
258 	    BUS_DMASYNC_PREWRITE);
259 
260 	dma->paddr = dma->map->dm_segs[0].ds_addr;
261 	if (kvap != NULL)
262 		*kvap = dma->vaddr;
263 
264 	return (0);
265 
266 unmap:
267 	bus_dmamem_unmap(dma->tag, dma->vaddr, size);
268 free:
269 	bus_dmamem_free(dma->tag, &dma->seg, 1);
270 destroy:
271 	bus_dmamap_destroy(dma->tag, dma->map);
272 	return (error);
273 }
274 
275 void
276 usbd_dma_contig_free(struct usbd_bus *bus, struct usbd_dma_info *dma)
277 {
278 	if (dma->map != NULL) {
279 		bus_dmamap_sync(bus->dmatag, dma->map, 0, dma->size,
280 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
281 		bus_dmamap_unload(bus->dmatag, dma->map);
282 		bus_dmamem_unmap(bus->dmatag, dma->vaddr, dma->size);
283 		bus_dmamem_free(bus->dmatag, &dma->seg, 1);
284 		bus_dmamap_destroy(bus->dmatag, dma->map);
285 		dma->map = NULL;
286 	}
287 }
288 
289 int
290 xhci_init(struct xhci_softc *sc)
291 {
292 	uint32_t hcr;
293 	int npage, error;
294 
295 	sc->sc_bus.usbrev = USBREV_3_0;
296 	sc->sc_bus.methods = &xhci_bus_methods;
297 	sc->sc_bus.pipe_size = sizeof(struct xhci_pipe);
298 
299 	sc->sc_oper_off = XREAD1(sc, XHCI_CAPLENGTH);
300 	sc->sc_door_off = XREAD4(sc, XHCI_DBOFF);
301 	sc->sc_runt_off = XREAD4(sc, XHCI_RTSOFF);
302 
303 	sc->sc_version = XREAD2(sc, XHCI_HCIVERSION);
304 	printf(", xHCI %x.%x\n", sc->sc_version >> 8, sc->sc_version & 0xff);
305 
306 #ifdef XHCI_DEBUG
307 	printf("%s: CAPLENGTH=%#lx\n", DEVNAME(sc), sc->sc_oper_off);
308 	printf("%s: DOORBELL=%#lx\n", DEVNAME(sc), sc->sc_door_off);
309 	printf("%s: RUNTIME=%#lx\n", DEVNAME(sc), sc->sc_runt_off);
310 #endif
311 
312 	error = xhci_reset(sc);
313 	if (error)
314 		return (error);
315 
316 	if (xhcixfer == NULL) {
317 		xhcixfer = malloc(sizeof(struct pool), M_DEVBUF, M_NOWAIT);
318 		if (xhcixfer == NULL) {
319 			printf("%s: unable to allocate pool descriptor\n",
320 			    DEVNAME(sc));
321 			return (ENOMEM);
322 		}
323 		pool_init(xhcixfer, sizeof(struct xhci_xfer), 0, IPL_SOFTUSB,
324 		    0, "xhcixfer", NULL);
325 	}
326 
327 	hcr = XREAD4(sc, XHCI_HCCPARAMS);
328 	sc->sc_ctxsize = XHCI_HCC_CSZ(hcr) ? 64 : 32;
329 	DPRINTF(("%s: %d bytes context\n", DEVNAME(sc), sc->sc_ctxsize));
330 
331 #ifdef XHCI_DEBUG
332 	hcr = XOREAD4(sc, XHCI_PAGESIZE);
333 	printf("%s: supported page size 0x%08x\n", DEVNAME(sc), hcr);
334 #endif
335 	/* Use 4K for the moment since it's easier. */
336 	sc->sc_pagesize = 4096;
337 
338 	/* Get port and device slot numbers. */
339 	hcr = XREAD4(sc, XHCI_HCSPARAMS1);
340 	sc->sc_noport = XHCI_HCS1_N_PORTS(hcr);
341 	sc->sc_noslot = XHCI_HCS1_DEVSLOT_MAX(hcr);
342 	DPRINTF(("%s: %d ports and %d slots\n", DEVNAME(sc), sc->sc_noport,
343 	    sc->sc_noslot));
344 
345 	/* Setup Device Context Base Address Array. */
346 	error = usbd_dma_contig_alloc(&sc->sc_bus, &sc->sc_dcbaa.dma,
347 	    (void **)&sc->sc_dcbaa.segs, (sc->sc_noslot + 1) * sizeof(uint64_t),
348 	    XHCI_DCBAA_ALIGN, sc->sc_pagesize);
349 	if (error)
350 		return (ENOMEM);
351 
352 	/* Setup command ring. */
353 	rw_init(&sc->sc_cmd_lock, "xhcicmd");
354 	error = xhci_ring_alloc(sc, &sc->sc_cmd_ring, XHCI_MAX_CMDS,
355 	    XHCI_CMDS_RING_ALIGN);
356 	if (error) {
357 		printf("%s: could not allocate command ring.\n", DEVNAME(sc));
358 		usbd_dma_contig_free(&sc->sc_bus, &sc->sc_dcbaa.dma);
359 		return (error);
360 	}
361 
362 	/* Setup one event ring and its segment table (ERST). */
363 	error = xhci_ring_alloc(sc, &sc->sc_evt_ring, XHCI_MAX_EVTS,
364 	    XHCI_EVTS_RING_ALIGN);
365 	if (error) {
366 		printf("%s: could not allocate event ring.\n", DEVNAME(sc));
367 		xhci_ring_free(sc, &sc->sc_cmd_ring);
368 		usbd_dma_contig_free(&sc->sc_bus, &sc->sc_dcbaa.dma);
369 		return (error);
370 	}
371 
372 	/* Allocate the required entry for the segment table. */
373 	error = usbd_dma_contig_alloc(&sc->sc_bus, &sc->sc_erst.dma,
374 	    (void **)&sc->sc_erst.segs, sizeof(struct xhci_erseg),
375 	    XHCI_ERST_ALIGN, XHCI_ERST_BOUNDARY);
376 	if (error) {
377 		printf("%s: could not allocate segment table.\n", DEVNAME(sc));
378 		xhci_ring_free(sc, &sc->sc_evt_ring);
379 		xhci_ring_free(sc, &sc->sc_cmd_ring);
380 		usbd_dma_contig_free(&sc->sc_bus, &sc->sc_dcbaa.dma);
381 		return (ENOMEM);
382 	}
383 
384 	/* Set our ring address and size in its corresponding segment. */
385 	sc->sc_erst.segs[0].er_addr = htole64(sc->sc_evt_ring.dma.paddr);
386 	sc->sc_erst.segs[0].er_size = htole32(XHCI_MAX_EVTS);
387 	sc->sc_erst.segs[0].er_rsvd = 0;
388 	bus_dmamap_sync(sc->sc_erst.dma.tag, sc->sc_erst.dma.map, 0,
389 	    sc->sc_erst.dma.size, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
390 
391 	/* Get the number of scratch pages and configure them if necessary. */
392 	hcr = XREAD4(sc, XHCI_HCSPARAMS2);
393 	npage = XHCI_HCS2_SPB_MAX(hcr);
394 	DPRINTF(("%s: %u scratch pages, ETE=%u, IST=0x%x\n", DEVNAME(sc), npage,
395 	   XHCI_HCS2_ETE(hcr), XHCI_HCS2_IST(hcr)));
396 
397 	if (npage > 0 && xhci_scratchpad_alloc(sc, npage)) {
398 		printf("%s: could not allocate scratchpad.\n", DEVNAME(sc));
399 		usbd_dma_contig_free(&sc->sc_bus, &sc->sc_erst.dma);
400 		xhci_ring_free(sc, &sc->sc_evt_ring);
401 		xhci_ring_free(sc, &sc->sc_cmd_ring);
402 		usbd_dma_contig_free(&sc->sc_bus, &sc->sc_dcbaa.dma);
403 		return (ENOMEM);
404 	}
405 
406 
407 	return (0);
408 }
409 
410 void
411 xhci_config(struct xhci_softc *sc)
412 {
413 	uint64_t paddr;
414 	uint32_t hcr;
415 
416 	/* Make sure to program a number of device slots we can handle. */
417 	if (sc->sc_noslot > USB_MAX_DEVICES)
418 		sc->sc_noslot = USB_MAX_DEVICES;
419 	hcr = XOREAD4(sc, XHCI_CONFIG) & ~XHCI_CONFIG_SLOTS_MASK;
420 	XOWRITE4(sc, XHCI_CONFIG, hcr | sc->sc_noslot);
421 
422 	/* Set the device context base array address. */
423 	paddr = (uint64_t)sc->sc_dcbaa.dma.paddr;
424 	XOWRITE4(sc, XHCI_DCBAAP_LO, (uint32_t)paddr);
425 	XOWRITE4(sc, XHCI_DCBAAP_HI, (uint32_t)(paddr >> 32));
426 
427 	DPRINTF(("%s: DCBAAP=%#x%#x\n", DEVNAME(sc),
428 	    XOREAD4(sc, XHCI_DCBAAP_HI), XOREAD4(sc, XHCI_DCBAAP_LO)));
429 
430 	/* Set the command ring address. */
431 	paddr = (uint64_t)sc->sc_cmd_ring.dma.paddr;
432 	XOWRITE4(sc, XHCI_CRCR_LO, ((uint32_t)paddr) | XHCI_CRCR_LO_RCS);
433 	XOWRITE4(sc, XHCI_CRCR_HI, (uint32_t)(paddr >> 32));
434 
435 	DPRINTF(("%s: CRCR=%#x%#x (%016llx)\n", DEVNAME(sc),
436 	    XOREAD4(sc, XHCI_CRCR_HI), XOREAD4(sc, XHCI_CRCR_LO), paddr));
437 
438 	/* Set the ERST count number to 1, since we use only one event ring. */
439 	XRWRITE4(sc, XHCI_ERSTSZ(0), XHCI_ERSTS_SET(1));
440 
441 	/* Set the segment table address. */
442 	paddr = (uint64_t)sc->sc_erst.dma.paddr;
443 	XRWRITE4(sc, XHCI_ERSTBA_LO(0), (uint32_t)paddr);
444 	XRWRITE4(sc, XHCI_ERSTBA_HI(0), (uint32_t)(paddr >> 32));
445 
446 	DPRINTF(("%s: ERSTBA=%#x%#x\n", DEVNAME(sc),
447 	    XRREAD4(sc, XHCI_ERSTBA_HI(0)), XRREAD4(sc, XHCI_ERSTBA_LO(0))));
448 
449 	/* Set the ring dequeue address. */
450 	paddr = (uint64_t)sc->sc_evt_ring.dma.paddr;
451 	XRWRITE4(sc, XHCI_ERDP_LO(0), (uint32_t)paddr);
452 	XRWRITE4(sc, XHCI_ERDP_HI(0), (uint32_t)(paddr >> 32));
453 
454 	DPRINTF(("%s: ERDP=%#x%#x\n", DEVNAME(sc),
455 	    XRREAD4(sc, XHCI_ERDP_HI(0)), XRREAD4(sc, XHCI_ERDP_LO(0))));
456 
457 	/* Enable interrupts. */
458 	hcr = XRREAD4(sc, XHCI_IMAN(0));
459 	XRWRITE4(sc, XHCI_IMAN(0), hcr | XHCI_IMAN_INTR_ENA);
460 
461 	/* Set default interrupt moderation. */
462 	XRWRITE4(sc, XHCI_IMOD(0), XHCI_IMOD_DEFAULT);
463 
464 	/* Allow event interrupt and start the controller. */
465 	XOWRITE4(sc, XHCI_USBCMD, XHCI_CMD_INTE|XHCI_CMD_RS);
466 
467 	DPRINTF(("%s: USBCMD=%#x\n", DEVNAME(sc), XOREAD4(sc, XHCI_USBCMD)));
468 	DPRINTF(("%s: IMAN=%#x\n", DEVNAME(sc), XRREAD4(sc, XHCI_IMAN(0))));
469 }
470 
471 int
472 xhci_detach(struct device *self, int flags)
473 {
474 	struct xhci_softc *sc = (struct xhci_softc *)self;
475 	int rv;
476 
477 	rv = config_detach_children(self, flags);
478 	if (rv != 0) {
479 		printf("%s: error while detaching %d\n", DEVNAME(sc), rv);
480 		return (rv);
481 	}
482 
483 	/* Since the hardware might already be gone, ignore the errors. */
484 	xhci_command_abort(sc);
485 
486 	xhci_reset(sc);
487 
488 	/* Disable interrupts. */
489 	XRWRITE4(sc, XHCI_IMOD(0), 0);
490 	XRWRITE4(sc, XHCI_IMAN(0), 0);
491 
492 	/* Clear the event ring address. */
493 	XRWRITE4(sc, XHCI_ERDP_LO(0), 0);
494 	XRWRITE4(sc, XHCI_ERDP_HI(0), 0);
495 
496 	XRWRITE4(sc, XHCI_ERSTBA_LO(0), 0);
497 	XRWRITE4(sc, XHCI_ERSTBA_HI(0), 0);
498 
499 	XRWRITE4(sc, XHCI_ERSTSZ(0), 0);
500 
501 	/* Clear the command ring address. */
502 	XOWRITE4(sc, XHCI_CRCR_LO, 0);
503 	XOWRITE4(sc, XHCI_CRCR_HI, 0);
504 
505 	XOWRITE4(sc, XHCI_DCBAAP_LO, 0);
506 	XOWRITE4(sc, XHCI_DCBAAP_HI, 0);
507 
508 	if (sc->sc_spad.npage > 0)
509 		xhci_scratchpad_free(sc);
510 
511 	usbd_dma_contig_free(&sc->sc_bus, &sc->sc_erst.dma);
512 	xhci_ring_free(sc, &sc->sc_evt_ring);
513 	xhci_ring_free(sc, &sc->sc_cmd_ring);
514 	usbd_dma_contig_free(&sc->sc_bus, &sc->sc_dcbaa.dma);
515 
516 	return (0);
517 }
518 
519 int
520 xhci_activate(struct device *self, int act)
521 {
522 	struct xhci_softc *sc = (struct xhci_softc *)self;
523 	int rv = 0;
524 
525 	switch (act) {
526 	case DVACT_RESUME:
527 		sc->sc_bus.use_polling++;
528 
529 		xhci_reset(sc);
530 		xhci_ring_reset(sc, &sc->sc_cmd_ring);
531 		xhci_ring_reset(sc, &sc->sc_evt_ring);
532 
533 		/* Renesas controllers, at least, need more time to resume. */
534 		usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);
535 
536 		xhci_config(sc);
537 
538 		sc->sc_bus.use_polling--;
539 		rv = config_activate_children(self, act);
540 		break;
541 	case DVACT_POWERDOWN:
542 		rv = config_activate_children(self, act);
543 		xhci_reset(sc);
544 		break;
545 	default:
546 		rv = config_activate_children(self, act);
547 		break;
548 	}
549 
550 	return (rv);
551 }
552 
553 int
554 xhci_reset(struct xhci_softc *sc)
555 {
556 	uint32_t hcr;
557 	int i;
558 
559 	XOWRITE4(sc, XHCI_USBCMD, 0);	/* Halt controller */
560 	for (i = 0; i < 100; i++) {
561 		usb_delay_ms(&sc->sc_bus, 1);
562 		hcr = XOREAD4(sc, XHCI_USBSTS) & XHCI_STS_HCH;
563 		if (hcr)
564 			break;
565 	}
566 
567 	if (!hcr)
568 		printf("%s: halt timeout\n", DEVNAME(sc));
569 
570 	XOWRITE4(sc, XHCI_USBCMD, XHCI_CMD_HCRST);
571 	for (i = 0; i < 100; i++) {
572 		usb_delay_ms(&sc->sc_bus, 1);
573 		hcr = (XOREAD4(sc, XHCI_USBCMD) & XHCI_CMD_HCRST) |
574 		    (XOREAD4(sc, XHCI_USBSTS) & XHCI_STS_CNR);
575 		if (!hcr)
576 			break;
577 	}
578 
579 	if (hcr) {
580 		printf("%s: reset timeout\n", DEVNAME(sc));
581 		return (EIO);
582 	}
583 
584 	return (0);
585 }
586 
587 
588 int
589 xhci_intr(void *v)
590 {
591 	struct xhci_softc *sc = v;
592 
593 	if (sc == NULL || sc->sc_bus.dying)
594 		return (0);
595 
596 	/* If we get an interrupt while polling, then just ignore it. */
597 	if (sc->sc_bus.use_polling) {
598 		DPRINTFN(16, ("xhci_intr: ignored interrupt while polling\n"));
599 		return (0);
600 	}
601 
602 	return (xhci_intr1(sc));
603 }
604 
605 int
606 xhci_intr1(struct xhci_softc *sc)
607 {
608 	uint32_t intrs;
609 
610 	intrs = XOREAD4(sc, XHCI_USBSTS);
611 	if (intrs == 0xffffffff) {
612 		sc->sc_bus.dying = 1;
613 		return (0);
614 	}
615 
616 	if ((intrs & XHCI_STS_EINT) == 0)
617 		return (0);
618 
619 	sc->sc_bus.no_intrs++;
620 
621 	if (intrs & XHCI_STS_HSE) {
622 		printf("%s: host system error\n", DEVNAME(sc));
623 		sc->sc_bus.dying = 1;
624 		return (1);
625 	}
626 
627 	XOWRITE4(sc, XHCI_USBSTS, intrs); /* Acknowledge */
628 	usb_schedsoftintr(&sc->sc_bus);
629 
630 	/* Acknowledge PCI interrupt */
631 	intrs = XRREAD4(sc, XHCI_IMAN(0));
632 	XRWRITE4(sc, XHCI_IMAN(0), intrs | XHCI_IMAN_INTR_PEND);
633 
634 	return (1);
635 }
636 
637 void
638 xhci_poll(struct usbd_bus *bus)
639 {
640 	struct xhci_softc *sc = (struct xhci_softc *)bus;
641 
642 	if (XOREAD4(sc, XHCI_USBSTS))
643 		xhci_intr1(sc);
644 }
645 
646 void
647 xhci_softintr(void *v)
648 {
649 	struct xhci_softc *sc = v;
650 
651 	if (sc->sc_bus.dying)
652 		return;
653 
654 	sc->sc_bus.intr_context++;
655 	xhci_event_dequeue(sc);
656 	sc->sc_bus.intr_context--;
657 }
658 
659 void
660 xhci_event_dequeue(struct xhci_softc *sc)
661 {
662 	struct xhci_trb *trb;
663 	uint64_t paddr;
664 	uint32_t status, flags;
665 
666 	while ((trb = xhci_ring_consume(sc, &sc->sc_evt_ring)) != NULL) {
667 		paddr = letoh64(trb->trb_paddr);
668 		status = letoh32(trb->trb_status);
669 		flags = letoh32(trb->trb_flags);
670 
671 		switch (flags & XHCI_TRB_TYPE_MASK) {
672 		case XHCI_EVT_XFER:
673 			xhci_event_xfer(sc, paddr, status, flags);
674 			break;
675 		case XHCI_EVT_CMD_COMPLETE:
676 			memcpy(&sc->sc_result_trb, trb, sizeof(*trb));
677 			xhci_event_command(sc, paddr);
678 			break;
679 		case XHCI_EVT_PORT_CHANGE:
680 			xhci_event_port_change(sc, paddr, status);
681 			break;
682 		case XHCI_EVT_HOST_CTRL:
683 			/* TODO */
684 			break;
685 		default:
686 #ifdef XHCI_DEBUG
687 			printf("event (%d): ", XHCI_TRB_TYPE(flags));
688 			xhci_dump_trb(trb);
689 #endif
690 			break;
691 		}
692 
693 	}
694 
695 	paddr = (uint64_t)DEQPTR(sc->sc_evt_ring);
696 	XRWRITE4(sc, XHCI_ERDP_LO(0), ((uint32_t)paddr) | XHCI_ERDP_LO_BUSY);
697 	XRWRITE4(sc, XHCI_ERDP_HI(0), (uint32_t)(paddr >> 32));
698 }
699 
700 void
701 xhci_skip_all(struct xhci_pipe *xp)
702 {
703 	struct usbd_xfer *xfer, *last;
704 
705 	if (xp->skip) {
706 		/*
707 		 * Find the last transfer to skip, this is necessary
708 		 * as xhci_xfer_done() posts new transfers which we
709 		 * don't want to skip
710 		 */
711 		last = SIMPLEQ_FIRST(&xp->pipe.queue);
712 		if (last == NULL)
713 			goto done;
714 		while ((xfer = SIMPLEQ_NEXT(last, next)) != NULL)
715 			last = xfer;
716 
717 		do {
718 			xfer = SIMPLEQ_FIRST(&xp->pipe.queue);
719 			if (xfer == NULL)
720 				goto done;
721 			DPRINTF(("%s: skipping %p\n", __func__, xfer));
722 			xfer->status = USBD_NORMAL_COMPLETION;
723 			xhci_xfer_done(xfer);
724 		} while (xfer != last);
725 	done:
726 		xp->skip = 0;
727 	}
728 }
729 
730 void
731 xhci_event_xfer(struct xhci_softc *sc, uint64_t paddr, uint32_t status,
732     uint32_t flags)
733 {
734 	struct xhci_pipe *xp;
735 	struct usbd_xfer *xfer;
736 	uint8_t dci, slot, code, xfertype;
737 	uint32_t remain;
738 	int trb_idx;
739 
740 	slot = XHCI_TRB_GET_SLOT(flags);
741 	dci = XHCI_TRB_GET_EP(flags);
742 	if (slot > sc->sc_noslot) {
743 		DPRINTF(("%s: incorrect slot (%u)\n", DEVNAME(sc), slot));
744 		return;
745 	}
746 
747 	xp = sc->sc_sdevs[slot].pipes[dci - 1];
748 	if (xp == NULL) {
749 		DPRINTF(("%s: incorrect dci (%u)\n", DEVNAME(sc), dci));
750 		return;
751 	}
752 
753 	code = XHCI_TRB_GET_CODE(status);
754 	remain = XHCI_TRB_REMAIN(status);
755 
756 	switch (code) {
757 	case XHCI_CODE_RING_UNDERRUN:
758 		DPRINTF(("%s: slot %u underrun with %zu TRB\n", DEVNAME(sc),
759 		    slot, xp->ring.ntrb - xp->free_trbs));
760 		xhci_skip_all(xp);
761 		return;
762 	case XHCI_CODE_RING_OVERRUN:
763 		DPRINTF(("%s: slot %u overrun with %zu TRB\n", DEVNAME(sc),
764 		    slot, xp->ring.ntrb - xp->free_trbs));
765 		xhci_skip_all(xp);
766 		return;
767 	case XHCI_CODE_MISSED_SRV:
768 		DPRINTF(("%s: slot %u missed srv with %zu TRB\n", DEVNAME(sc),
769 		    slot, xp->ring.ntrb - xp->free_trbs));
770 		xp->skip = 1;
771 		return;
772 	default:
773 		break;
774 	}
775 
776 	trb_idx = (paddr - xp->ring.dma.paddr) / sizeof(struct xhci_trb);
777 	if (trb_idx < 0 || trb_idx >= xp->ring.ntrb) {
778 		printf("%s: wrong trb index (%u) max is %zu\n", DEVNAME(sc),
779 		    trb_idx, xp->ring.ntrb - 1);
780 		return;
781 	}
782 
783 	xfer = xp->pending_xfers[trb_idx];
784 	if (xfer == NULL) {
785 		DPRINTF(("%s: NULL xfer pointer\n", DEVNAME(sc)));
786 		return;
787 	}
788 
789 	if (remain > xfer->length)
790 		remain = xfer->length;
791 
792 	xfertype = UE_GET_XFERTYPE(xfer->pipe->endpoint->edesc->bmAttributes);
793 
794 	switch (xfertype) {
795 	case UE_BULK:
796 	case UE_INTERRUPT:
797 	case UE_CONTROL:
798 		if (xhci_event_xfer_generic(sc, xfer, xp, remain, trb_idx,
799 		    code, slot, dci))
800 			return;
801 		break;
802 	case UE_ISOCHRONOUS:
803 		if (xhci_event_xfer_isoc(xfer, xp, remain, trb_idx))
804 			return;
805 		break;
806 	default:
807 		panic("xhci_event_xfer: unknown xfer type %u", xfertype);
808 	}
809 
810 	xhci_xfer_done(xfer);
811 }
812 
813 uint32_t
814 xhci_xfer_length_generic(struct xhci_xfer *xx, struct xhci_pipe *xp,
815     int trb_idx)
816 {
817 	int	 trb0_idx;
818 	uint32_t len = 0, type;
819 
820 	trb0_idx =
821 	    ((xx->index + xp->ring.ntrb) - xx->ntrb) % (xp->ring.ntrb - 1);
822 
823 	while (1) {
824 		type = letoh32(xp->ring.trbs[trb0_idx].trb_flags) &
825 		    XHCI_TRB_TYPE_MASK;
826 		if (type == XHCI_TRB_TYPE_NORMAL || type == XHCI_TRB_TYPE_DATA)
827 			len += XHCI_TRB_LEN(letoh32(
828 			    xp->ring.trbs[trb0_idx].trb_status));
829 		if (trb0_idx == trb_idx)
830 			break;
831 		if (++trb0_idx == xp->ring.ntrb)
832 			trb0_idx = 0;
833 	}
834 	return len;
835 }
836 
837 int
838 xhci_event_xfer_generic(struct xhci_softc *sc, struct usbd_xfer *xfer,
839     struct xhci_pipe *xp, uint32_t remain, int trb_idx,
840     uint8_t code, uint8_t slot, uint8_t dci)
841 {
842 	struct xhci_xfer *xx = (struct xhci_xfer *)xfer;
843 
844 	switch (code) {
845 	case XHCI_CODE_SUCCESS:
846 		if (xfer->actlen == 0) {
847 			if (remain)
848 				xfer->actlen =
849 				    xhci_xfer_length_generic(xx, xp, trb_idx) -
850 				    remain;
851 			else
852 				xfer->actlen = xfer->length;
853 		}
854 		xfer->status = USBD_NORMAL_COMPLETION;
855 		break;
856 	case XHCI_CODE_SHORT_XFER:
857 		/*
858 		 * Use values from the transfer TRB instead of the status TRB.
859 		 */
860 		if (xfer->actlen == 0)
861 			xfer->actlen =
862 			    xhci_xfer_length_generic(xx, xp, trb_idx) - remain;
863 		/*
864 		 * If this is not the last TRB of a transfer, we should
865 		 * theoretically clear the IOC at the end of the chain
866 		 * but the HC might have already processed it before we
867 		 * had a chance to schedule the softinterrupt.
868 		 */
869 		if (xx->index != trb_idx) {
870 			DPRINTF(("%s: short xfer %p for %u\n",
871 			    DEVNAME(sc), xfer, xx->index));
872 			return (1);
873 		}
874 		xfer->status = USBD_NORMAL_COMPLETION;
875 		break;
876 	case XHCI_CODE_TXERR:
877 	case XHCI_CODE_SPLITERR:
878 		DPRINTF(("%s: txerr? code %d\n", DEVNAME(sc), code));
879 		xfer->status = USBD_IOERROR;
880 		break;
881 	case XHCI_CODE_STALL:
882 	case XHCI_CODE_BABBLE:
883 		DPRINTF(("%s: babble code %d\n", DEVNAME(sc), code));
884 		/* Prevent any timeout to kick in. */
885 		timeout_del(&xfer->timeout_handle);
886 		usb_rem_task(xfer->device, &xfer->abort_task);
887 
888 		/* We need to report this condition for umass(4). */
889 		if (code == XHCI_CODE_STALL)
890 			xp->halted = USBD_STALLED;
891 		else
892 			xp->halted = USBD_IOERROR;
893 		/*
894 		 * Since the stack might try to start a new transfer as
895 		 * soon as a pending one finishes, make sure the endpoint
896 		 * is fully reset before calling usb_transfer_complete().
897 		 */
898 		xp->aborted_xfer = xfer;
899 		xhci_cmd_reset_ep_async(sc, slot, dci);
900 		return (1);
901 	case XHCI_CODE_XFER_STOPPED:
902 	case XHCI_CODE_XFER_STOPINV:
903 		/* Endpoint stopped while processing a TD. */
904 		if (xfer == xp->aborted_xfer) {
905 			DPRINTF(("%s: stopped xfer=%p\n", __func__, xfer));
906 		    	return (1);
907 		}
908 
909 		/* FALLTHROUGH */
910 	default:
911 		DPRINTF(("%s: unhandled code %d\n", DEVNAME(sc), code));
912 		xfer->status = USBD_IOERROR;
913 		xp->halted = 1;
914 		break;
915 	}
916 
917 	return (0);
918 }
919 
920 int
921 xhci_event_xfer_isoc(struct usbd_xfer *xfer, struct xhci_pipe *xp,
922     uint32_t remain, int trb_idx)
923 {
924 	struct usbd_xfer *skipxfer;
925 	struct xhci_xfer *xx = (struct xhci_xfer *)xfer;
926 	int trb0_idx, frame_idx = 0;
927 
928 	KASSERT(xx->index >= 0);
929 	trb0_idx =
930 	    ((xx->index + xp->ring.ntrb) - xx->ntrb) % (xp->ring.ntrb - 1);
931 
932 	/* Find the according frame index for this TRB. */
933 	while (trb0_idx != trb_idx) {
934 		if ((letoh32(xp->ring.trbs[trb0_idx].trb_flags) &
935 		    XHCI_TRB_TYPE_MASK) == XHCI_TRB_TYPE_ISOCH)
936 			frame_idx++;
937 		if (trb0_idx++ == (xp->ring.ntrb - 1))
938 			trb0_idx = 0;
939 	}
940 
941 	/*
942 	 * If we queued two TRBs for a frame and this is the second TRB,
943 	 * check if the first TRB needs accounting since it might not have
944 	 * raised an interrupt in case of full data received.
945 	 */
946 	if ((letoh32(xp->ring.trbs[trb_idx].trb_flags) & XHCI_TRB_TYPE_MASK) ==
947 	    XHCI_TRB_TYPE_NORMAL) {
948 		frame_idx--;
949 		if (trb_idx == 0)
950 			trb0_idx = xp->ring.ntrb - 2;
951 		else
952 			trb0_idx = trb_idx - 1;
953 		if (xfer->frlengths[frame_idx] == 0) {
954 			xfer->frlengths[frame_idx] = XHCI_TRB_LEN(letoh32(
955 			    xp->ring.trbs[trb0_idx].trb_status));
956 		}
957 	}
958 
959 	xfer->frlengths[frame_idx] +=
960 	    XHCI_TRB_LEN(letoh32(xp->ring.trbs[trb_idx].trb_status)) - remain;
961 	xfer->actlen += xfer->frlengths[frame_idx];
962 
963 	if (xx->index != trb_idx)
964 		return (1);
965 
966 	if (xp->skip) {
967 		while (1) {
968 			skipxfer = SIMPLEQ_FIRST(&xp->pipe.queue);
969 			if (skipxfer == xfer || skipxfer == NULL)
970 				break;
971 			DPRINTF(("%s: skipping %p\n", __func__, skipxfer));
972 			skipxfer->status = USBD_NORMAL_COMPLETION;
973 			xhci_xfer_done(skipxfer);
974 		}
975 		xp->skip = 0;
976 	}
977 
978 	xfer->status = USBD_NORMAL_COMPLETION;
979 
980 	return (0);
981 }
982 
983 void
984 xhci_event_command(struct xhci_softc *sc, uint64_t paddr)
985 {
986 	struct xhci_trb *trb;
987 	struct xhci_pipe *xp;
988 	uint32_t flags;
989 	uint8_t dci, slot;
990 	int trb_idx, status;
991 
992 	trb_idx = (paddr - sc->sc_cmd_ring.dma.paddr) / sizeof(*trb);
993 	if (trb_idx < 0 || trb_idx >= sc->sc_cmd_ring.ntrb) {
994 		printf("%s: wrong trb index (%u) max is %zu\n", DEVNAME(sc),
995 		    trb_idx, sc->sc_cmd_ring.ntrb - 1);
996 		return;
997 	}
998 
999 	trb = &sc->sc_cmd_ring.trbs[trb_idx];
1000 
1001 	bus_dmamap_sync(sc->sc_cmd_ring.dma.tag, sc->sc_cmd_ring.dma.map,
1002 	    TRBOFF(&sc->sc_cmd_ring, trb), sizeof(struct xhci_trb),
1003 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1004 
1005 	flags = letoh32(trb->trb_flags);
1006 
1007 	slot = XHCI_TRB_GET_SLOT(flags);
1008 	dci = XHCI_TRB_GET_EP(flags);
1009 
1010 	switch (flags & XHCI_TRB_TYPE_MASK) {
1011 	case XHCI_CMD_RESET_EP:
1012 		xp = sc->sc_sdevs[slot].pipes[dci - 1];
1013 		if (xp == NULL)
1014 			break;
1015 
1016 		/* Update the dequeue pointer past the last TRB. */
1017 		xhci_cmd_set_tr_deq_async(sc, xp->slot, xp->dci,
1018 		    DEQPTR(xp->ring) | xp->ring.toggle);
1019 		break;
1020 	case XHCI_CMD_SET_TR_DEQ:
1021 		xp = sc->sc_sdevs[slot].pipes[dci - 1];
1022 		if (xp == NULL)
1023 			break;
1024 
1025 		status = xp->halted;
1026 		xp->halted = 0;
1027 		if (xp->aborted_xfer != NULL) {
1028 			xp->aborted_xfer->status = status;
1029 			xhci_xfer_done(xp->aborted_xfer);
1030 			wakeup(xp);
1031 		}
1032 		break;
1033 	case XHCI_CMD_CONFIG_EP:
1034 	case XHCI_CMD_STOP_EP:
1035 	case XHCI_CMD_DISABLE_SLOT:
1036 	case XHCI_CMD_ENABLE_SLOT:
1037 	case XHCI_CMD_ADDRESS_DEVICE:
1038 	case XHCI_CMD_EVAL_CTX:
1039 	case XHCI_CMD_NOOP:
1040 		/* All these commands are synchronous. */
1041 		KASSERT(sc->sc_cmd_trb == trb);
1042 		sc->sc_cmd_trb = NULL;
1043 		wakeup(&sc->sc_cmd_trb);
1044 		break;
1045 	default:
1046 		DPRINTF(("%s: unexpected command %x\n", DEVNAME(sc), flags));
1047 	}
1048 }
1049 
1050 void
1051 xhci_event_port_change(struct xhci_softc *sc, uint64_t paddr, uint32_t status)
1052 {
1053 	struct usbd_xfer *xfer = sc->sc_intrxfer;
1054 	uint32_t port = XHCI_TRB_PORTID(paddr);
1055 	uint8_t *p;
1056 
1057 	if (XHCI_TRB_GET_CODE(status) != XHCI_CODE_SUCCESS) {
1058 		DPRINTF(("%s: failed port status event\n", DEVNAME(sc)));
1059 		return;
1060 	}
1061 
1062 	if (xfer == NULL)
1063 		return;
1064 
1065 	p = KERNADDR(&xfer->dmabuf, 0);
1066 	memset(p, 0, xfer->length);
1067 
1068 	p[port/8] |= 1 << (port%8);
1069 	DPRINTF(("%s: port=%d change=0x%02x\n", DEVNAME(sc), port, *p));
1070 
1071 	xfer->actlen = xfer->length;
1072 	xfer->status = USBD_NORMAL_COMPLETION;
1073 
1074 	usb_transfer_complete(xfer);
1075 }
1076 
1077 void
1078 xhci_xfer_done(struct usbd_xfer *xfer)
1079 {
1080 	struct xhci_pipe *xp = (struct xhci_pipe *)xfer->pipe;
1081 	struct xhci_xfer *xx = (struct xhci_xfer *)xfer;
1082 	int ntrb, i;
1083 
1084 	splsoftassert(IPL_SOFTUSB);
1085 
1086 #ifdef XHCI_DEBUG
1087 	if (xx->index < 0 || xp->pending_xfers[xx->index] == NULL) {
1088 		printf("%s: xfer=%p done (idx=%d, ntrb=%zd)\n", __func__,
1089 		    xfer, xx->index, xx->ntrb);
1090 	}
1091 #endif
1092 
1093 	if (xp->aborted_xfer == xfer)
1094 		xp->aborted_xfer = NULL;
1095 
1096 	for (ntrb = 0, i = xx->index; ntrb < xx->ntrb; ntrb++, i--) {
1097 		xp->pending_xfers[i] = NULL;
1098 		if (i == 0)
1099 			i = (xp->ring.ntrb - 1);
1100 	}
1101 	xp->free_trbs += xx->ntrb;
1102 	xx->index = -1;
1103 	xx->ntrb = 0;
1104 
1105 	timeout_del(&xfer->timeout_handle);
1106 	usb_rem_task(xfer->device, &xfer->abort_task);
1107 	usb_transfer_complete(xfer);
1108 }
1109 
1110 /*
1111  * Calculate the Device Context Index (DCI) for endpoints as stated
1112  * in section 4.5.1 of xHCI specification r1.1.
1113  */
1114 static inline uint8_t
1115 xhci_ed2dci(usb_endpoint_descriptor_t *ed)
1116 {
1117 	uint8_t dir;
1118 
1119 	if (UE_GET_XFERTYPE(ed->bmAttributes) == UE_CONTROL)
1120 		return (UE_GET_ADDR(ed->bEndpointAddress) * 2 + 1);
1121 
1122 	if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN)
1123 		dir = 1;
1124 	else
1125 		dir = 0;
1126 
1127 	return (UE_GET_ADDR(ed->bEndpointAddress) * 2 + dir);
1128 }
1129 
1130 usbd_status
1131 xhci_pipe_open(struct usbd_pipe *pipe)
1132 {
1133 	struct xhci_softc *sc = (struct xhci_softc *)pipe->device->bus;
1134 	struct xhci_pipe *xp = (struct xhci_pipe *)pipe;
1135 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
1136 	uint8_t slot = 0, xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
1137 	int error;
1138 
1139 	KASSERT(xp->slot == 0);
1140 
1141 	if (sc->sc_bus.dying)
1142 		return (USBD_IOERROR);
1143 
1144 	/* Root Hub */
1145 	if (pipe->device->depth == 0) {
1146 		switch (ed->bEndpointAddress) {
1147 		case USB_CONTROL_ENDPOINT:
1148 			pipe->methods = &xhci_root_ctrl_methods;
1149 			break;
1150 		case UE_DIR_IN | XHCI_INTR_ENDPT:
1151 			pipe->methods = &xhci_root_intr_methods;
1152 			break;
1153 		default:
1154 			pipe->methods = NULL;
1155 			return (USBD_INVAL);
1156 		}
1157 		return (USBD_NORMAL_COMPLETION);
1158 	}
1159 
1160 #if 0
1161 	/* Issue a noop to check if the command ring is correctly configured. */
1162 	xhci_cmd_noop(sc);
1163 #endif
1164 
1165 	switch (xfertype) {
1166 	case UE_CONTROL:
1167 		pipe->methods = &xhci_device_ctrl_methods;
1168 
1169 		/*
1170 		 * Get a slot and init the device's contexts.
1171 		 *
1172 		 * Since the control enpoint, represented as the default
1173 		 * pipe, is always opened first we are dealing with a
1174 		 * new device.  Put a new slot in the ENABLED state.
1175 		 *
1176 		 */
1177 		error = xhci_cmd_slot_control(sc, &slot, 1);
1178 		if (error || slot == 0 || slot > sc->sc_noslot)
1179 			return (USBD_INVAL);
1180 
1181 		if (xhci_softdev_alloc(sc, slot)) {
1182 			xhci_cmd_slot_control(sc, &slot, 0);
1183 			return (USBD_NOMEM);
1184 		}
1185 
1186 		break;
1187 	case UE_ISOCHRONOUS:
1188 		pipe->methods = &xhci_device_isoc_methods;
1189 		break;
1190 	case UE_BULK:
1191 		pipe->methods = &xhci_device_bulk_methods;
1192 		break;
1193 	case UE_INTERRUPT:
1194 		pipe->methods = &xhci_device_intr_methods;
1195 		break;
1196 	default:
1197 		return (USBD_INVAL);
1198 	}
1199 
1200 	/*
1201 	 * Our USBD Bus Interface is pipe-oriented but for most of the
1202 	 * operations we need to access a device context, so keep track
1203 	 * of the slot ID in every pipe.
1204 	 */
1205 	if (slot == 0)
1206 		slot = ((struct xhci_pipe *)pipe->device->default_pipe)->slot;
1207 
1208 	xp->slot = slot;
1209 	xp->dci = xhci_ed2dci(ed);
1210 
1211 	if (xhci_pipe_init(sc, pipe)) {
1212 		xhci_cmd_slot_control(sc, &slot, 0);
1213 		return (USBD_IOERROR);
1214 	}
1215 
1216 	return (USBD_NORMAL_COMPLETION);
1217 }
1218 
1219 /*
1220  * Set the maximum Endpoint Service Interface Time (ESIT) payload and
1221  * the average TRB buffer length for an endpoint.
1222  */
1223 static inline uint32_t
1224 xhci_get_txinfo(struct xhci_softc *sc, struct usbd_pipe *pipe)
1225 {
1226 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
1227 	uint32_t mep, atl, mps = UGETW(ed->wMaxPacketSize);
1228 
1229 	switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
1230 	case UE_CONTROL:
1231 		mep = 0;
1232 		atl = 8;
1233 		break;
1234 	case UE_INTERRUPT:
1235 	case UE_ISOCHRONOUS:
1236 		if (pipe->device->speed == USB_SPEED_SUPER) {
1237 			/*  XXX Read the companion descriptor */
1238 		}
1239 
1240 		mep = (UE_GET_TRANS(mps) + 1) * UE_GET_SIZE(mps);
1241 		atl = mep;
1242 		break;
1243 	case UE_BULK:
1244 	default:
1245 		mep = 0;
1246 		atl = 0;
1247 	}
1248 
1249 	return (XHCI_EPCTX_MAX_ESIT_PAYLOAD(mep) | XHCI_EPCTX_AVG_TRB_LEN(atl));
1250 }
1251 
1252 static inline uint32_t
1253 xhci_linear_interval(usb_endpoint_descriptor_t *ed)
1254 {
1255 	uint32_t ival = min(max(1, ed->bInterval), 255);
1256 
1257 	return (fls(ival) - 1);
1258 }
1259 
1260 static inline uint32_t
1261 xhci_exponential_interval(usb_endpoint_descriptor_t *ed)
1262 {
1263 	uint32_t ival = min(max(1, ed->bInterval), 16);
1264 
1265 	return (ival - 1);
1266 }
1267 /*
1268  * Return interval for endpoint expressed in 2^(ival) * 125us.
1269  *
1270  * See section 6.2.3.6 of xHCI r1.1 Specification for more details.
1271  */
1272 uint32_t
1273 xhci_pipe_interval(struct usbd_pipe *pipe)
1274 {
1275 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
1276 	uint8_t speed = pipe->device->speed;
1277 	uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
1278 	uint32_t ival;
1279 
1280 	if (xfertype == UE_CONTROL || xfertype == UE_BULK) {
1281 		/* Control and Bulk endpoints never NAKs. */
1282 		ival = 0;
1283 	} else {
1284 		switch (speed) {
1285 		case USB_SPEED_FULL:
1286 			if (xfertype == UE_ISOCHRONOUS) {
1287 				/* Convert 1-2^(15)ms into 3-18 */
1288 				ival = xhci_exponential_interval(ed) + 3;
1289 				break;
1290 			}
1291 			/* FALLTHROUGH */
1292 		case USB_SPEED_LOW:
1293 			/* Convert 1-255ms into 3-10 */
1294 			ival = xhci_linear_interval(ed) + 3;
1295 			break;
1296 		case USB_SPEED_HIGH:
1297 		case USB_SPEED_SUPER:
1298 		default:
1299 			/* Convert 1-2^(15) * 125us into 0-15 */
1300 			ival = xhci_exponential_interval(ed);
1301 			break;
1302 		}
1303 	}
1304 
1305 	KASSERT(ival <= 15);
1306 	return (XHCI_EPCTX_SET_IVAL(ival));
1307 }
1308 
1309 uint32_t
1310 xhci_pipe_maxburst(struct usbd_pipe *pipe)
1311 {
1312 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
1313 	uint32_t mps = UGETW(ed->wMaxPacketSize);
1314 	uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
1315 	uint32_t maxb = 0;
1316 
1317 	switch (pipe->device->speed) {
1318 	case USB_SPEED_HIGH:
1319 		if (xfertype == UE_ISOCHRONOUS || xfertype == UE_INTERRUPT)
1320 			maxb = UE_GET_TRANS(mps);
1321 		break;
1322 	case USB_SPEED_SUPER:
1323 		/*  XXX Read the companion descriptor */
1324 	default:
1325 		break;
1326 	}
1327 
1328 	return (maxb);
1329 }
1330 
1331 static inline uint32_t
1332 xhci_last_valid_dci(struct xhci_pipe **pipes, struct xhci_pipe *ignore)
1333 {
1334 	struct xhci_pipe *lxp;
1335 	int i;
1336 
1337 	/* Find the last valid Endpoint Context. */
1338 	for (i = 30; i >= 0; i--) {
1339 		lxp = pipes[i];
1340 		if (lxp != NULL && lxp != ignore)
1341 			return XHCI_SCTX_DCI(lxp->dci);
1342 	}
1343 
1344 	return 0;
1345 }
1346 
1347 int
1348 xhci_context_setup(struct xhci_softc *sc, struct usbd_pipe *pipe)
1349 {
1350 	struct xhci_pipe *xp = (struct xhci_pipe *)pipe;
1351 	struct xhci_soft_dev *sdev = &sc->sc_sdevs[xp->slot];
1352 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
1353 	uint32_t mps = UGETW(ed->wMaxPacketSize);
1354 	uint8_t xfertype = UE_GET_XFERTYPE(ed->bmAttributes);
1355 	uint8_t speed, cerr = 0;
1356 	uint32_t route = 0, rhport = 0;
1357 	struct usbd_device *hub;
1358 
1359 	/*
1360 	 * Calculate the Route String.  Assume that there is no hub with
1361 	 * more than 15 ports and that they all have a detph < 6.  See
1362 	 * section 8.9 of USB 3.1 Specification for more details.
1363 	 */
1364 	for (hub = pipe->device; hub->myhub->depth; hub = hub->myhub) {
1365 		uint32_t port = hub->powersrc->portno;
1366 		uint32_t depth = hub->myhub->depth;
1367 
1368 		route |= port << (4 * (depth - 1));
1369 	}
1370 
1371 	/* Get Root Hub port */
1372 	rhport = hub->powersrc->portno;
1373 
1374 	switch (pipe->device->speed) {
1375 	case USB_SPEED_LOW:
1376 		speed = XHCI_SPEED_LOW;
1377 		break;
1378 	case USB_SPEED_FULL:
1379 		speed = XHCI_SPEED_FULL;
1380 		break;
1381 	case USB_SPEED_HIGH:
1382 		speed = XHCI_SPEED_HIGH;
1383 		break;
1384 	case USB_SPEED_SUPER:
1385 		speed = XHCI_SPEED_SUPER;
1386 		break;
1387 	default:
1388 		return (USBD_INVAL);
1389 	}
1390 
1391 	/* Setup the endpoint context */
1392 	if (xfertype != UE_ISOCHRONOUS)
1393 		cerr = 3;
1394 
1395 	if ((ed->bEndpointAddress & UE_DIR_IN) || (xfertype == UE_CONTROL))
1396 		xfertype |= 0x4;
1397 
1398 	sdev->ep_ctx[xp->dci-1]->info_lo = htole32(xhci_pipe_interval(pipe));
1399 	sdev->ep_ctx[xp->dci-1]->info_hi = htole32(
1400 	    XHCI_EPCTX_SET_MPS(UE_GET_SIZE(mps)) |
1401 	    XHCI_EPCTX_SET_MAXB(xhci_pipe_maxburst(pipe)) |
1402 	    XHCI_EPCTX_SET_EPTYPE(xfertype) | XHCI_EPCTX_SET_CERR(cerr)
1403 	);
1404 	sdev->ep_ctx[xp->dci-1]->txinfo = htole32(xhci_get_txinfo(sc, pipe));
1405 	sdev->ep_ctx[xp->dci-1]->deqp = htole64(
1406 	    DEQPTR(xp->ring) | xp->ring.toggle
1407 	);
1408 
1409 	/* Unmask the new endoint */
1410 	sdev->input_ctx->drop_flags = 0;
1411 	sdev->input_ctx->add_flags = htole32(XHCI_INCTX_MASK_DCI(xp->dci));
1412 
1413 	/* Setup the slot context */
1414 	sdev->slot_ctx->info_lo = htole32(
1415 	    xhci_last_valid_dci(sdev->pipes, NULL) | XHCI_SCTX_SPEED(speed) |
1416 	    XHCI_SCTX_ROUTE(route)
1417 	);
1418 	sdev->slot_ctx->info_hi = htole32(XHCI_SCTX_RHPORT(rhport));
1419 	sdev->slot_ctx->tt = 0;
1420 	sdev->slot_ctx->state = 0;
1421 
1422 /* XXX */
1423 #define UHUB_IS_MTT(dev) (dev->ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT)
1424 	/*
1425 	 * If we are opening the interrupt pipe of a hub, update its
1426 	 * context before putting it in the CONFIGURED state.
1427 	 */
1428 	if (pipe->device->hub != NULL) {
1429 		int nports = pipe->device->hub->nports;
1430 
1431 		sdev->slot_ctx->info_lo |= htole32(XHCI_SCTX_HUB(1));
1432 		sdev->slot_ctx->info_hi |= htole32(XHCI_SCTX_NPORTS(nports));
1433 
1434 		if (UHUB_IS_MTT(pipe->device))
1435 			sdev->slot_ctx->info_lo |= htole32(XHCI_SCTX_MTT(1));
1436 
1437 		sdev->slot_ctx->tt |= htole32(
1438 		    XHCI_SCTX_TT_THINK_TIME(pipe->device->hub->ttthink)
1439 		);
1440 	}
1441 
1442 	/*
1443 	 * If this is a Low or Full Speed device below an external High
1444 	 * Speed hub, it needs some TT love.
1445 	 */
1446 	if (speed < XHCI_SPEED_HIGH && pipe->device->myhsport != NULL) {
1447 		struct usbd_device *hshub = pipe->device->myhsport->parent;
1448 		uint8_t slot = ((struct xhci_pipe *)hshub->default_pipe)->slot;
1449 
1450 		if (UHUB_IS_MTT(hshub))
1451 			sdev->slot_ctx->info_lo |= htole32(XHCI_SCTX_MTT(1));
1452 
1453 		sdev->slot_ctx->tt |= htole32(
1454 		    XHCI_SCTX_TT_HUB_SID(slot) |
1455 		    XHCI_SCTX_TT_PORT_NUM(pipe->device->myhsport->portno)
1456 		);
1457 	}
1458 #undef UHUB_IS_MTT
1459 
1460 	/* Unmask the slot context */
1461 	sdev->input_ctx->add_flags |= htole32(XHCI_INCTX_MASK_DCI(0));
1462 
1463 	bus_dmamap_sync(sdev->ictx_dma.tag, sdev->ictx_dma.map, 0,
1464 	    sc->sc_pagesize, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1465 
1466 	return (0);
1467 }
1468 
1469 int
1470 xhci_pipe_init(struct xhci_softc *sc, struct usbd_pipe *pipe)
1471 {
1472 	struct xhci_pipe *xp = (struct xhci_pipe *)pipe;
1473 	struct xhci_soft_dev *sdev = &sc->sc_sdevs[xp->slot];
1474 	int error;
1475 
1476 #ifdef XHCI_DEBUG
1477 	struct usbd_device *dev = pipe->device;
1478 	printf("%s: pipe=%p addr=%d depth=%d port=%d speed=%d dev %d dci %u"
1479 	    " (epAddr=0x%x)\n", __func__, pipe, dev->address, dev->depth,
1480 	    dev->powersrc->portno, dev->speed, xp->slot, xp->dci,
1481 	    pipe->endpoint->edesc->bEndpointAddress);
1482 #endif
1483 
1484 	if (xhci_ring_alloc(sc, &xp->ring, XHCI_MAX_XFER, XHCI_XFER_RING_ALIGN))
1485 		return (ENOMEM);
1486 
1487 	xp->free_trbs = xp->ring.ntrb;
1488 	xp->halted = 0;
1489 
1490 	sdev->pipes[xp->dci - 1] = xp;
1491 
1492 	error = xhci_context_setup(sc, pipe);
1493 	if (error)
1494 		return (error);
1495 
1496 	if (xp->dci == 1) {
1497 		/*
1498 		 * If we are opening the default pipe, the Slot should
1499 		 * be in the ENABLED state.  Issue an "Address Device"
1500 		 * with BSR=1 to put the device in the DEFAULT state.
1501 		 * We cannot jump directly to the ADDRESSED state with
1502 		 * BSR=0 because some Low/Full speed devices won't accept
1503 		 * a SET_ADDRESS command before we've read their device
1504 		 * descriptor.
1505 		 */
1506 		error = xhci_cmd_set_address(sc, xp->slot,
1507 		    sdev->ictx_dma.paddr, XHCI_TRB_BSR);
1508 	} else {
1509 		error = xhci_cmd_configure_ep(sc, xp->slot,
1510 		    sdev->ictx_dma.paddr);
1511 	}
1512 
1513 	if (error) {
1514 		xhci_ring_free(sc, &xp->ring);
1515 		return (EIO);
1516 	}
1517 
1518 	return (0);
1519 }
1520 
1521 void
1522 xhci_pipe_close(struct usbd_pipe *pipe)
1523 {
1524 	struct xhci_softc *sc = (struct xhci_softc *)pipe->device->bus;
1525 	struct xhci_pipe *xp = (struct xhci_pipe *)pipe;
1526 	struct xhci_soft_dev *sdev = &sc->sc_sdevs[xp->slot];
1527 
1528 	/* Root Hub */
1529 	if (pipe->device->depth == 0)
1530 		return;
1531 
1532 	/* Mask the endpoint */
1533 	sdev->input_ctx->drop_flags = htole32(XHCI_INCTX_MASK_DCI(xp->dci));
1534 	sdev->input_ctx->add_flags = 0;
1535 
1536 	/* Update last valid Endpoint Context */
1537 	sdev->slot_ctx->info_lo &= htole32(~XHCI_SCTX_DCI(31));
1538 	sdev->slot_ctx->info_lo |= htole32(xhci_last_valid_dci(sdev->pipes, xp));
1539 
1540 	/* Clear the Endpoint Context */
1541 	memset(sdev->ep_ctx[xp->dci - 1], 0, sizeof(struct xhci_epctx));
1542 
1543 	bus_dmamap_sync(sdev->ictx_dma.tag, sdev->ictx_dma.map, 0,
1544 	    sc->sc_pagesize, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1545 
1546 	if (xhci_cmd_configure_ep(sc, xp->slot, sdev->ictx_dma.paddr))
1547 		DPRINTF(("%s: error clearing ep (%d)\n", DEVNAME(sc), xp->dci));
1548 
1549 	xhci_ring_free(sc, &xp->ring);
1550 	sdev->pipes[xp->dci - 1] = NULL;
1551 
1552 	/*
1553 	 * If we are closing the default pipe, the device is probably
1554 	 * gone, so put its slot in the DISABLED state.
1555 	 */
1556 	if (xp->dci == 1) {
1557 		xhci_cmd_slot_control(sc, &xp->slot, 0);
1558 		xhci_softdev_free(sc, xp->slot);
1559 	}
1560 }
1561 
1562 /*
1563  * Transition a device from DEFAULT to ADDRESSED Slot state, this hook
1564  * is needed for Low/Full speed devices.
1565  *
1566  * See section 4.5.3 of USB 3.1 Specification for more details.
1567  */
1568 int
1569 xhci_setaddr(struct usbd_device *dev, int addr)
1570 {
1571 	struct xhci_softc *sc = (struct xhci_softc *)dev->bus;
1572 	struct xhci_pipe *xp = (struct xhci_pipe *)dev->default_pipe;
1573 	struct xhci_soft_dev *sdev = &sc->sc_sdevs[xp->slot];
1574 	int error;
1575 
1576 	/* Root Hub */
1577 	if (dev->depth == 0)
1578 		return (0);
1579 
1580 	KASSERT(xp->dci == 1);
1581 
1582 	error = xhci_context_setup(sc, dev->default_pipe);
1583 	if (error)
1584 		return (error);
1585 
1586 	error = xhci_cmd_set_address(sc, xp->slot, sdev->ictx_dma.paddr, 0);
1587 
1588 #ifdef XHCI_DEBUG
1589 	if (error == 0) {
1590 		struct xhci_sctx *sctx;
1591 		uint8_t addr;
1592 
1593 		bus_dmamap_sync(sdev->octx_dma.tag, sdev->octx_dma.map, 0,
1594 		    sc->sc_pagesize, BUS_DMASYNC_POSTREAD);
1595 
1596 		/* Get output slot context. */
1597 		sctx = (struct xhci_sctx *)sdev->octx_dma.vaddr;
1598 		addr = XHCI_SCTX_DEV_ADDR(letoh32(sctx->state));
1599 		error = (addr == 0);
1600 
1601 		printf("%s: dev %d addr %d\n", DEVNAME(sc), xp->slot, addr);
1602 	}
1603 #endif
1604 
1605 	return (error);
1606 }
1607 
1608 struct usbd_xfer *
1609 xhci_allocx(struct usbd_bus *bus)
1610 {
1611 	return (pool_get(xhcixfer, PR_NOWAIT | PR_ZERO));
1612 }
1613 
1614 void
1615 xhci_freex(struct usbd_bus *bus, struct usbd_xfer *xfer)
1616 {
1617 	pool_put(xhcixfer, xfer);
1618 }
1619 
1620 int
1621 xhci_scratchpad_alloc(struct xhci_softc *sc, int npage)
1622 {
1623 	uint64_t *pte;
1624 	int error, i;
1625 
1626 	/* Allocate the required entry for the table. */
1627 	error = usbd_dma_contig_alloc(&sc->sc_bus, &sc->sc_spad.table_dma,
1628 	    (void **)&pte, npage * sizeof(uint64_t), XHCI_SPAD_TABLE_ALIGN,
1629 	    sc->sc_pagesize);
1630 	if (error)
1631 		return (ENOMEM);
1632 
1633 	/* Allocate pages. XXX does not need to be contiguous. */
1634 	error = usbd_dma_contig_alloc(&sc->sc_bus, &sc->sc_spad.pages_dma,
1635 	    NULL, npage * sc->sc_pagesize, sc->sc_pagesize, 0);
1636 	if (error) {
1637 		usbd_dma_contig_free(&sc->sc_bus, &sc->sc_spad.table_dma);
1638 		return (ENOMEM);
1639 	}
1640 
1641 	for (i = 0; i < npage; i++) {
1642 		pte[i] = htole64(
1643 		    sc->sc_spad.pages_dma.paddr + (i * sc->sc_pagesize)
1644 		);
1645 	}
1646 
1647 	bus_dmamap_sync(sc->sc_spad.table_dma.tag, sc->sc_spad.table_dma.map, 0,
1648 	    npage * sizeof(uint64_t), BUS_DMASYNC_PREREAD |
1649 	    BUS_DMASYNC_PREWRITE);
1650 
1651 	/*  Entry 0 points to the table of scratchpad pointers. */
1652 	sc->sc_dcbaa.segs[0] = htole64(sc->sc_spad.table_dma.paddr);
1653 	bus_dmamap_sync(sc->sc_dcbaa.dma.tag, sc->sc_dcbaa.dma.map, 0,
1654 	    sizeof(uint64_t), BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1655 
1656 	sc->sc_spad.npage = npage;
1657 
1658 	return (0);
1659 }
1660 
1661 void
1662 xhci_scratchpad_free(struct xhci_softc *sc)
1663 {
1664 	sc->sc_dcbaa.segs[0] = 0;
1665 	bus_dmamap_sync(sc->sc_dcbaa.dma.tag, sc->sc_dcbaa.dma.map, 0,
1666 	    sizeof(uint64_t), BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1667 
1668 	usbd_dma_contig_free(&sc->sc_bus, &sc->sc_spad.pages_dma);
1669 	usbd_dma_contig_free(&sc->sc_bus, &sc->sc_spad.table_dma);
1670 }
1671 
1672 int
1673 xhci_ring_alloc(struct xhci_softc *sc, struct xhci_ring *ring, size_t ntrb,
1674     size_t alignment)
1675 {
1676 	size_t size;
1677 	int error;
1678 
1679 	size = ntrb * sizeof(struct xhci_trb);
1680 
1681 	error = usbd_dma_contig_alloc(&sc->sc_bus, &ring->dma,
1682 	    (void **)&ring->trbs, size, alignment, XHCI_RING_BOUNDARY);
1683 	if (error)
1684 		return (error);
1685 
1686 	ring->ntrb = ntrb;
1687 
1688 	xhci_ring_reset(sc, ring);
1689 
1690 	return (0);
1691 }
1692 
1693 void
1694 xhci_ring_free(struct xhci_softc *sc, struct xhci_ring *ring)
1695 {
1696 	usbd_dma_contig_free(&sc->sc_bus, &ring->dma);
1697 }
1698 
1699 void
1700 xhci_ring_reset(struct xhci_softc *sc, struct xhci_ring *ring)
1701 {
1702 	size_t size;
1703 
1704 	size = ring->ntrb * sizeof(struct xhci_trb);
1705 
1706 	memset(ring->trbs, 0, size);
1707 
1708 	ring->index = 0;
1709 	ring->toggle = XHCI_TRB_CYCLE;
1710 
1711 	/*
1712 	 * Since all our rings use only one segment, at least for
1713 	 * the moment, link their tail to their head.
1714 	 */
1715 	if (ring != &sc->sc_evt_ring) {
1716 		struct xhci_trb *trb = &ring->trbs[ring->ntrb - 1];
1717 
1718 		trb->trb_paddr = htole64(ring->dma.paddr);
1719 		trb->trb_flags = htole32(XHCI_TRB_TYPE_LINK | XHCI_TRB_LINKSEG |
1720 		    XHCI_TRB_CYCLE);
1721 		bus_dmamap_sync(ring->dma.tag, ring->dma.map, 0, size,
1722 		    BUS_DMASYNC_PREWRITE);
1723 	} else
1724 		bus_dmamap_sync(ring->dma.tag, ring->dma.map, 0, size,
1725 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1726 }
1727 
1728 struct xhci_trb*
1729 xhci_ring_consume(struct xhci_softc *sc, struct xhci_ring *ring)
1730 {
1731 	struct xhci_trb *trb = &ring->trbs[ring->index];
1732 
1733 	KASSERT(ring->index < ring->ntrb);
1734 
1735 	bus_dmamap_sync(ring->dma.tag, ring->dma.map, TRBOFF(ring, trb),
1736 	    sizeof(struct xhci_trb), BUS_DMASYNC_POSTREAD);
1737 
1738 	/* Make sure this TRB can be consumed. */
1739 	if (ring->toggle != (letoh32(trb->trb_flags) & XHCI_TRB_CYCLE))
1740 		return (NULL);
1741 
1742 	ring->index++;
1743 
1744 	if (ring->index == ring->ntrb) {
1745 		ring->index = 0;
1746 		ring->toggle ^= 1;
1747 	}
1748 
1749 	return (trb);
1750 }
1751 
1752 struct xhci_trb*
1753 xhci_ring_produce(struct xhci_softc *sc, struct xhci_ring *ring)
1754 {
1755 	struct xhci_trb *lnk, *trb;
1756 
1757 	KASSERT(ring->index < ring->ntrb);
1758 
1759 	/* Setup the link TRB after the previous TRB is done. */
1760 	if (ring->index == 0) {
1761 		lnk = &ring->trbs[ring->ntrb - 1];
1762 		trb = &ring->trbs[ring->ntrb - 2];
1763 
1764 		bus_dmamap_sync(ring->dma.tag, ring->dma.map, TRBOFF(ring, lnk),
1765 		    sizeof(struct xhci_trb), BUS_DMASYNC_POSTREAD |
1766 		    BUS_DMASYNC_POSTWRITE);
1767 
1768 		lnk->trb_flags &= htole32(~XHCI_TRB_CHAIN);
1769 		if (letoh32(trb->trb_flags) & XHCI_TRB_CHAIN)
1770 			lnk->trb_flags |= htole32(XHCI_TRB_CHAIN);
1771 
1772 		bus_dmamap_sync(ring->dma.tag, ring->dma.map, TRBOFF(ring, lnk),
1773 		    sizeof(struct xhci_trb), BUS_DMASYNC_PREWRITE);
1774 
1775 		lnk->trb_flags ^= htole32(XHCI_TRB_CYCLE);
1776 
1777 		bus_dmamap_sync(ring->dma.tag, ring->dma.map, TRBOFF(ring, lnk),
1778 		    sizeof(struct xhci_trb), BUS_DMASYNC_PREWRITE);
1779 	}
1780 
1781 	trb = &ring->trbs[ring->index++];
1782 	bus_dmamap_sync(ring->dma.tag, ring->dma.map, TRBOFF(ring, trb),
1783 	    sizeof(struct xhci_trb), BUS_DMASYNC_POSTREAD |
1784 	    BUS_DMASYNC_POSTWRITE);
1785 
1786 	/* Toggle cycle state of the link TRB and skip it. */
1787 	if (ring->index == (ring->ntrb - 1)) {
1788 		ring->index = 0;
1789 		ring->toggle ^= 1;
1790 	}
1791 
1792 	return (trb);
1793 }
1794 
1795 struct xhci_trb *
1796 xhci_xfer_get_trb(struct xhci_softc *sc, struct usbd_xfer *xfer,
1797     uint8_t *togglep, int last)
1798 {
1799 	struct xhci_pipe *xp = (struct xhci_pipe *)xfer->pipe;
1800 	struct xhci_xfer *xx = (struct xhci_xfer *)xfer;
1801 
1802 	KASSERT(xp->free_trbs >= 1);
1803 	xp->free_trbs--;
1804 	*togglep = xp->ring.toggle;
1805 
1806 	switch (last) {
1807 	case -1:	/* This will be a zero-length TD. */
1808 		xp->pending_xfers[xp->ring.index] = NULL;
1809 		break;
1810 	case 0:		/* This will be in a chain. */
1811 		xp->pending_xfers[xp->ring.index] = xfer;
1812 		xx->index = -2;
1813 		xx->ntrb += 1;
1814 		break;
1815 	case 1:		/* This will terminate a chain. */
1816 		xp->pending_xfers[xp->ring.index] = xfer;
1817 		xx->index = xp->ring.index;
1818 		xx->ntrb += 1;
1819 		break;
1820 	}
1821 
1822 	return (xhci_ring_produce(sc, &xp->ring));
1823 }
1824 
1825 int
1826 xhci_command_submit(struct xhci_softc *sc, struct xhci_trb *trb0, int timeout)
1827 {
1828 	struct xhci_trb *trb;
1829 	int s, error = 0;
1830 
1831 	KASSERT(timeout == 0 || sc->sc_cmd_trb == NULL);
1832 
1833 	trb0->trb_flags |= htole32(sc->sc_cmd_ring.toggle);
1834 
1835 	trb = xhci_ring_produce(sc, &sc->sc_cmd_ring);
1836 	if (trb == NULL)
1837 		return (EAGAIN);
1838 	trb->trb_paddr = trb0->trb_paddr;
1839 	trb->trb_status = trb0->trb_status;
1840 	bus_dmamap_sync(sc->sc_cmd_ring.dma.tag, sc->sc_cmd_ring.dma.map,
1841 	    TRBOFF(&sc->sc_cmd_ring, trb), sizeof(struct xhci_trb),
1842 	    BUS_DMASYNC_PREWRITE);
1843 
1844 	trb->trb_flags = trb0->trb_flags;
1845 	bus_dmamap_sync(sc->sc_cmd_ring.dma.tag, sc->sc_cmd_ring.dma.map,
1846 	    TRBOFF(&sc->sc_cmd_ring, trb), sizeof(struct xhci_trb),
1847 	    BUS_DMASYNC_PREWRITE);
1848 
1849 	if (timeout == 0) {
1850 		XDWRITE4(sc, XHCI_DOORBELL(0), 0);
1851 		return (0);
1852 	}
1853 
1854 	rw_assert_wrlock(&sc->sc_cmd_lock);
1855 
1856 	s = splusb();
1857 	sc->sc_cmd_trb = trb;
1858 	XDWRITE4(sc, XHCI_DOORBELL(0), 0);
1859 	error = tsleep_nsec(&sc->sc_cmd_trb, PZERO, "xhcicmd", timeout);
1860 	if (error) {
1861 #ifdef XHCI_DEBUG
1862 		printf("%s: tsleep() = %d\n", __func__, error);
1863 		printf("cmd = %d ", XHCI_TRB_TYPE(letoh32(trb->trb_flags)));
1864 		xhci_dump_trb(trb);
1865 #endif
1866 		KASSERT(sc->sc_cmd_trb == trb);
1867 		sc->sc_cmd_trb = NULL;
1868 		splx(s);
1869 		return (error);
1870 	}
1871 	splx(s);
1872 
1873 	memcpy(trb0, &sc->sc_result_trb, sizeof(struct xhci_trb));
1874 
1875 	if (XHCI_TRB_GET_CODE(letoh32(trb0->trb_status)) == XHCI_CODE_SUCCESS)
1876 		return (0);
1877 
1878 #ifdef XHCI_DEBUG
1879 	printf("%s: event error code=%d, result=%d  \n", DEVNAME(sc),
1880 	    XHCI_TRB_GET_CODE(letoh32(trb0->trb_status)),
1881 	    XHCI_TRB_TYPE(letoh32(trb0->trb_flags)));
1882 	xhci_dump_trb(trb0);
1883 #endif
1884 	return (EIO);
1885 }
1886 
1887 int
1888 xhci_command_abort(struct xhci_softc *sc)
1889 {
1890 	uint32_t reg;
1891 	int i;
1892 
1893 	reg = XOREAD4(sc, XHCI_CRCR_LO);
1894 	if ((reg & XHCI_CRCR_LO_CRR) == 0)
1895 		return (0);
1896 
1897 	XOWRITE4(sc, XHCI_CRCR_LO, reg | XHCI_CRCR_LO_CA);
1898 	XOWRITE4(sc, XHCI_CRCR_HI, 0);
1899 
1900 	for (i = 0; i < 250; i++) {
1901 		usb_delay_ms(&sc->sc_bus, 1);
1902 		reg = XOREAD4(sc, XHCI_CRCR_LO) & XHCI_CRCR_LO_CRR;
1903 		if (!reg)
1904 			break;
1905 	}
1906 
1907 	if (reg) {
1908 		printf("%s: command ring abort timeout\n", DEVNAME(sc));
1909 		return (1);
1910 	}
1911 
1912 	return (0);
1913 }
1914 
1915 int
1916 xhci_cmd_configure_ep(struct xhci_softc *sc, uint8_t slot, uint64_t addr)
1917 {
1918 	struct xhci_trb trb;
1919 	int error;
1920 
1921 	DPRINTF(("%s: %s dev %u\n", DEVNAME(sc), __func__, slot));
1922 
1923 	trb.trb_paddr = htole64(addr);
1924 	trb.trb_status = 0;
1925 	trb.trb_flags = htole32(
1926 	    XHCI_TRB_SET_SLOT(slot) | XHCI_CMD_CONFIG_EP
1927 	);
1928 
1929 	rw_enter_write(&sc->sc_cmd_lock);
1930 	error = xhci_command_submit(sc, &trb, XHCI_CMD_TIMEOUT);
1931 	rw_exit_write(&sc->sc_cmd_lock);
1932 	return (error);
1933 }
1934 
1935 int
1936 xhci_cmd_stop_ep(struct xhci_softc *sc, uint8_t slot, uint8_t dci)
1937 {
1938 	struct xhci_trb trb;
1939 	int error;
1940 
1941 	DPRINTF(("%s: %s dev %u dci %u\n", DEVNAME(sc), __func__, slot, dci));
1942 
1943 	trb.trb_paddr = 0;
1944 	trb.trb_status = 0;
1945 	trb.trb_flags = htole32(
1946 	    XHCI_TRB_SET_SLOT(slot) | XHCI_TRB_SET_EP(dci) | XHCI_CMD_STOP_EP
1947 	);
1948 
1949 	rw_enter_write(&sc->sc_cmd_lock);
1950 	error = xhci_command_submit(sc, &trb, XHCI_CMD_TIMEOUT);
1951 	rw_exit_write(&sc->sc_cmd_lock);
1952 	return (error);
1953 }
1954 
1955 void
1956 xhci_cmd_reset_ep_async(struct xhci_softc *sc, uint8_t slot, uint8_t dci)
1957 {
1958 	struct xhci_trb trb;
1959 
1960 	DPRINTF(("%s: %s dev %u dci %u\n", DEVNAME(sc), __func__, slot, dci));
1961 
1962 	trb.trb_paddr = 0;
1963 	trb.trb_status = 0;
1964 	trb.trb_flags = htole32(
1965 	    XHCI_TRB_SET_SLOT(slot) | XHCI_TRB_SET_EP(dci) | XHCI_CMD_RESET_EP
1966 	);
1967 
1968 	xhci_command_submit(sc, &trb, 0);
1969 }
1970 
1971 void
1972 xhci_cmd_set_tr_deq_async(struct xhci_softc *sc, uint8_t slot, uint8_t dci,
1973    uint64_t addr)
1974 {
1975 	struct xhci_trb trb;
1976 
1977 	DPRINTF(("%s: %s dev %u dci %u\n", DEVNAME(sc), __func__, slot, dci));
1978 
1979 	trb.trb_paddr = htole64(addr);
1980 	trb.trb_status = 0;
1981 	trb.trb_flags = htole32(
1982 	    XHCI_TRB_SET_SLOT(slot) | XHCI_TRB_SET_EP(dci) | XHCI_CMD_SET_TR_DEQ
1983 	);
1984 
1985 	xhci_command_submit(sc, &trb, 0);
1986 }
1987 
1988 int
1989 xhci_cmd_slot_control(struct xhci_softc *sc, uint8_t *slotp, int enable)
1990 {
1991 	struct xhci_trb trb;
1992 	int error;
1993 
1994 	DPRINTF(("%s: %s\n", DEVNAME(sc), __func__));
1995 
1996 	trb.trb_paddr = 0;
1997 	trb.trb_status = 0;
1998 	if (enable)
1999 		trb.trb_flags = htole32(XHCI_CMD_ENABLE_SLOT);
2000 	else
2001 		trb.trb_flags = htole32(
2002 			XHCI_TRB_SET_SLOT(*slotp) | XHCI_CMD_DISABLE_SLOT
2003 		);
2004 
2005 	rw_enter_write(&sc->sc_cmd_lock);
2006 	error = xhci_command_submit(sc, &trb, XHCI_CMD_TIMEOUT);
2007 	rw_exit_write(&sc->sc_cmd_lock);
2008 	if (error != 0)
2009 		return (EIO);
2010 
2011 	if (enable)
2012 		*slotp = XHCI_TRB_GET_SLOT(letoh32(trb.trb_flags));
2013 
2014 	return (0);
2015 }
2016 
2017 int
2018 xhci_cmd_set_address(struct xhci_softc *sc, uint8_t slot, uint64_t addr,
2019     uint32_t bsr)
2020 {
2021 	struct xhci_trb trb;
2022 	int error;
2023 
2024 	DPRINTF(("%s: %s BSR=%u\n", DEVNAME(sc), __func__, bsr ? 1 : 0));
2025 
2026 	trb.trb_paddr = htole64(addr);
2027 	trb.trb_status = 0;
2028 	trb.trb_flags = htole32(
2029 	    XHCI_TRB_SET_SLOT(slot) | XHCI_CMD_ADDRESS_DEVICE | bsr
2030 	);
2031 
2032 	rw_enter_write(&sc->sc_cmd_lock);
2033 	error = xhci_command_submit(sc, &trb, XHCI_CMD_TIMEOUT);
2034 	rw_exit_write(&sc->sc_cmd_lock);
2035 	return (error);
2036 }
2037 
2038 int
2039 xhci_cmd_evaluate_ctx(struct xhci_softc *sc, uint8_t slot, uint64_t addr)
2040 {
2041 	struct xhci_trb trb;
2042 	int error;
2043 
2044 	DPRINTF(("%s: %s dev %u\n", DEVNAME(sc), __func__, slot));
2045 
2046 	trb.trb_paddr = htole64(addr);
2047 	trb.trb_status = 0;
2048 	trb.trb_flags = htole32(
2049 	    XHCI_TRB_SET_SLOT(slot) | XHCI_CMD_EVAL_CTX
2050 	);
2051 
2052 	rw_enter_write(&sc->sc_cmd_lock);
2053 	error = xhci_command_submit(sc, &trb, XHCI_CMD_TIMEOUT);
2054 	rw_exit_write(&sc->sc_cmd_lock);
2055 	return (error);
2056 }
2057 
2058 #ifdef XHCI_DEBUG
2059 int
2060 xhci_cmd_noop(struct xhci_softc *sc)
2061 {
2062 	struct xhci_trb trb;
2063 	int error;
2064 
2065 	DPRINTF(("%s: %s\n", DEVNAME(sc), __func__));
2066 
2067 	trb.trb_paddr = 0;
2068 	trb.trb_status = 0;
2069 	trb.trb_flags = htole32(XHCI_CMD_NOOP);
2070 
2071 	rw_enter_write(&sc->sc_cmd_lock);
2072 	error = xhci_command_submit(sc, &trb, XHCI_CMD_TIMEOUT);
2073 	rw_exit_write(&sc->sc_cmd_lock);
2074 	return (error);
2075 }
2076 #endif
2077 
2078 int
2079 xhci_softdev_alloc(struct xhci_softc *sc, uint8_t slot)
2080 {
2081 	struct xhci_soft_dev *sdev = &sc->sc_sdevs[slot];
2082 	int i, error;
2083 	uint8_t *kva;
2084 
2085 	/*
2086 	 * Setup input context.  Even with 64 byte context size, it
2087 	 * fits into the smallest supported page size, so use that.
2088 	 */
2089 	error = usbd_dma_contig_alloc(&sc->sc_bus, &sdev->ictx_dma,
2090 	    (void **)&kva, sc->sc_pagesize, XHCI_ICTX_ALIGN, sc->sc_pagesize);
2091 	if (error)
2092 		return (ENOMEM);
2093 
2094 	sdev->input_ctx = (struct xhci_inctx *)kva;
2095 	sdev->slot_ctx = (struct xhci_sctx *)(kva + sc->sc_ctxsize);
2096 	for (i = 0; i < 31; i++)
2097 		sdev->ep_ctx[i] =
2098 		    (struct xhci_epctx *)(kva + (i + 2) * sc->sc_ctxsize);
2099 
2100 	DPRINTF(("%s: dev %d, input=%p slot=%p ep0=%p\n", DEVNAME(sc),
2101 	 slot, sdev->input_ctx, sdev->slot_ctx, sdev->ep_ctx[0]));
2102 
2103 	/* Setup output context */
2104 	error = usbd_dma_contig_alloc(&sc->sc_bus, &sdev->octx_dma, NULL,
2105 	    sc->sc_pagesize, XHCI_OCTX_ALIGN, sc->sc_pagesize);
2106 	if (error) {
2107 		usbd_dma_contig_free(&sc->sc_bus, &sdev->ictx_dma);
2108 		return (ENOMEM);
2109 	}
2110 
2111 	memset(&sdev->pipes, 0, sizeof(sdev->pipes));
2112 
2113 	DPRINTF(("%s: dev %d, setting DCBAA to 0x%016llx\n", DEVNAME(sc),
2114 	    slot, (long long)sdev->octx_dma.paddr));
2115 
2116 	sc->sc_dcbaa.segs[slot] = htole64(sdev->octx_dma.paddr);
2117 	bus_dmamap_sync(sc->sc_dcbaa.dma.tag, sc->sc_dcbaa.dma.map,
2118 	    slot * sizeof(uint64_t), sizeof(uint64_t), BUS_DMASYNC_PREREAD |
2119 	    BUS_DMASYNC_PREWRITE);
2120 
2121 	return (0);
2122 }
2123 
2124 void
2125 xhci_softdev_free(struct xhci_softc *sc, uint8_t slot)
2126 {
2127 	struct xhci_soft_dev *sdev = &sc->sc_sdevs[slot];
2128 
2129 	sc->sc_dcbaa.segs[slot] = 0;
2130 	bus_dmamap_sync(sc->sc_dcbaa.dma.tag, sc->sc_dcbaa.dma.map,
2131 	    slot * sizeof(uint64_t), sizeof(uint64_t), BUS_DMASYNC_PREREAD |
2132 	    BUS_DMASYNC_PREWRITE);
2133 
2134 	usbd_dma_contig_free(&sc->sc_bus, &sdev->octx_dma);
2135 	usbd_dma_contig_free(&sc->sc_bus, &sdev->ictx_dma);
2136 
2137 	memset(sdev, 0, sizeof(struct xhci_soft_dev));
2138 }
2139 
2140 /* Root hub descriptors. */
2141 usb_device_descriptor_t xhci_devd = {
2142 	USB_DEVICE_DESCRIPTOR_SIZE,
2143 	UDESC_DEVICE,		/* type */
2144 	{0x00, 0x03},		/* USB version */
2145 	UDCLASS_HUB,		/* class */
2146 	UDSUBCLASS_HUB,		/* subclass */
2147 	UDPROTO_HSHUBSTT,	/* protocol */
2148 	9,			/* max packet */
2149 	{0},{0},{0x00,0x01},	/* device id */
2150 	1,2,0,			/* string indexes */
2151 	1			/* # of configurations */
2152 };
2153 
2154 const usb_config_descriptor_t xhci_confd = {
2155 	USB_CONFIG_DESCRIPTOR_SIZE,
2156 	UDESC_CONFIG,
2157 	{USB_CONFIG_DESCRIPTOR_SIZE +
2158 	 USB_INTERFACE_DESCRIPTOR_SIZE +
2159 	 USB_ENDPOINT_DESCRIPTOR_SIZE},
2160 	1,
2161 	1,
2162 	0,
2163 	UC_BUS_POWERED | UC_SELF_POWERED,
2164 	0                      /* max power */
2165 };
2166 
2167 const usb_interface_descriptor_t xhci_ifcd = {
2168 	USB_INTERFACE_DESCRIPTOR_SIZE,
2169 	UDESC_INTERFACE,
2170 	0,
2171 	0,
2172 	1,
2173 	UICLASS_HUB,
2174 	UISUBCLASS_HUB,
2175 	UIPROTO_HSHUBSTT,
2176 	0
2177 };
2178 
2179 const usb_endpoint_descriptor_t xhci_endpd = {
2180 	USB_ENDPOINT_DESCRIPTOR_SIZE,
2181 	UDESC_ENDPOINT,
2182 	UE_DIR_IN | XHCI_INTR_ENDPT,
2183 	UE_INTERRUPT,
2184 	{2, 0},                 /* max 15 ports */
2185 	255
2186 };
2187 
2188 const usb_endpoint_ss_comp_descriptor_t xhci_endpcd = {
2189 	USB_ENDPOINT_SS_COMP_DESCRIPTOR_SIZE,
2190 	UDESC_ENDPOINT_SS_COMP,
2191 	0,
2192 	0,
2193 	{0, 0}
2194 };
2195 
2196 const usb_hub_descriptor_t xhci_hubd = {
2197 	USB_HUB_DESCRIPTOR_SIZE,
2198 	UDESC_SS_HUB,
2199 	0,
2200 	{0,0},
2201 	0,
2202 	0,
2203 	{0},
2204 };
2205 
2206 void
2207 xhci_abort_xfer(struct usbd_xfer *xfer, usbd_status status)
2208 {
2209 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
2210 	struct xhci_pipe *xp = (struct xhci_pipe *)xfer->pipe;
2211 	int error;
2212 
2213 	splsoftassert(IPL_SOFTUSB);
2214 
2215 	DPRINTF(("%s: xfer=%p status=%s err=%s actlen=%d len=%d idx=%d\n",
2216 	    __func__, xfer, usbd_errstr(xfer->status), usbd_errstr(status),
2217 	    xfer->actlen, xfer->length, ((struct xhci_xfer *)xfer)->index));
2218 
2219 	/* XXX The stack should not call abort() in this case. */
2220 	if (sc->sc_bus.dying || xfer->status == USBD_NOT_STARTED) {
2221 		xfer->status = status;
2222 		timeout_del(&xfer->timeout_handle);
2223 		usb_rem_task(xfer->device, &xfer->abort_task);
2224 		usb_transfer_complete(xfer);
2225 		return;
2226 	}
2227 
2228 	/* Transfer is already done. */
2229 	if (xfer->status != USBD_IN_PROGRESS) {
2230 		DPRINTF(("%s: already done \n", __func__));
2231 		return;
2232 	}
2233 
2234 	/* Prevent any timeout to kick in. */
2235 	timeout_del(&xfer->timeout_handle);
2236 	usb_rem_task(xfer->device, &xfer->abort_task);
2237 
2238 	/* Indicate that we are aborting this transfer. */
2239 	xp->halted = status;
2240 	xp->aborted_xfer = xfer;
2241 
2242 	/* Stop the endpoint and wait until the hardware says so. */
2243 	if (xhci_cmd_stop_ep(sc, xp->slot, xp->dci)) {
2244 		DPRINTF(("%s: error stopping endpoint\n", DEVNAME(sc)));
2245 		/* Assume the device is gone. */
2246 		xp->halted = 0;
2247 		xp->aborted_xfer = NULL;
2248 		xfer->status = status;
2249 		usb_transfer_complete(xfer);
2250 		return;
2251 	}
2252 
2253 	/*
2254 	 * The transfer was already completed when we stopped the
2255 	 * endpoint, no need to move the dequeue pointer past its
2256 	 * TRBs.
2257 	 */
2258 	if (xp->aborted_xfer == NULL) {
2259 		DPRINTF(("%s: done before stopping the endpoint\n", __func__));
2260 		xp->halted = 0;
2261 		return;
2262 	}
2263 
2264 	/*
2265 	 * At this stage the endpoint has been stopped, so update its
2266 	 * dequeue pointer past the last TRB of the transfer.
2267 	 *
2268 	 * Note: This assumes that only one transfer per endpoint has
2269 	 *	 pending TRBs on the ring.
2270 	 */
2271 	xhci_cmd_set_tr_deq_async(sc, xp->slot, xp->dci,
2272 	    DEQPTR(xp->ring) | xp->ring.toggle);
2273 	error = tsleep_nsec(xp, PZERO, "xhciab", XHCI_CMD_TIMEOUT);
2274 	if (error)
2275 		printf("%s: timeout aborting transfer\n", DEVNAME(sc));
2276 }
2277 
2278 void
2279 xhci_timeout(void *addr)
2280 {
2281 	struct usbd_xfer *xfer = addr;
2282 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
2283 
2284 	if (sc->sc_bus.dying) {
2285 		xhci_timeout_task(addr);
2286 		return;
2287 	}
2288 
2289 	usb_init_task(&xfer->abort_task, xhci_timeout_task, addr,
2290 	    USB_TASK_TYPE_ABORT);
2291 	usb_add_task(xfer->device, &xfer->abort_task);
2292 }
2293 
2294 void
2295 xhci_timeout_task(void *addr)
2296 {
2297 	struct usbd_xfer *xfer = addr;
2298 	int s;
2299 
2300 	s = splusb();
2301 	xhci_abort_xfer(xfer, USBD_TIMEOUT);
2302 	splx(s);
2303 }
2304 
2305 usbd_status
2306 xhci_root_ctrl_transfer(struct usbd_xfer *xfer)
2307 {
2308 	usbd_status err;
2309 
2310 	err = usb_insert_transfer(xfer);
2311 	if (err)
2312 		return (err);
2313 
2314 	return (xhci_root_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2315 }
2316 
2317 usbd_status
2318 xhci_root_ctrl_start(struct usbd_xfer *xfer)
2319 {
2320 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
2321 	usb_port_status_t ps;
2322 	usb_device_request_t *req;
2323 	void *buf = NULL;
2324 	usb_hub_descriptor_t hubd;
2325 	usbd_status err;
2326 	int s, len, value, index;
2327 	int l, totlen = 0;
2328 	int port, i;
2329 	uint32_t v;
2330 
2331 	KASSERT(xfer->rqflags & URQ_REQUEST);
2332 
2333 	if (sc->sc_bus.dying)
2334 		return (USBD_IOERROR);
2335 
2336 	req = &xfer->request;
2337 
2338 	DPRINTFN(4,("%s: type=0x%02x request=%02x\n", __func__,
2339 	    req->bmRequestType, req->bRequest));
2340 
2341 	len = UGETW(req->wLength);
2342 	value = UGETW(req->wValue);
2343 	index = UGETW(req->wIndex);
2344 
2345 	if (len != 0)
2346 		buf = KERNADDR(&xfer->dmabuf, 0);
2347 
2348 #define C(x,y) ((x) | ((y) << 8))
2349 	switch(C(req->bRequest, req->bmRequestType)) {
2350 	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
2351 	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
2352 	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
2353 		/*
2354 		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
2355 		 * for the integrated root hub.
2356 		 */
2357 		break;
2358 	case C(UR_GET_CONFIG, UT_READ_DEVICE):
2359 		if (len > 0) {
2360 			*(uint8_t *)buf = sc->sc_conf;
2361 			totlen = 1;
2362 		}
2363 		break;
2364 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
2365 		DPRINTFN(8,("xhci_root_ctrl_start: wValue=0x%04x\n", value));
2366 		switch(value >> 8) {
2367 		case UDESC_DEVICE:
2368 			if ((value & 0xff) != 0) {
2369 				err = USBD_IOERROR;
2370 				goto ret;
2371 			}
2372 			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
2373 			USETW(xhci_devd.idVendor, sc->sc_id_vendor);
2374 			memcpy(buf, &xhci_devd, l);
2375 			break;
2376 		/*
2377 		 * We can't really operate at another speed, but the spec says
2378 		 * we need this descriptor.
2379 		 */
2380 		case UDESC_OTHER_SPEED_CONFIGURATION:
2381 		case UDESC_CONFIG:
2382 			if ((value & 0xff) != 0) {
2383 				err = USBD_IOERROR;
2384 				goto ret;
2385 			}
2386 			totlen = l = min(len, USB_CONFIG_DESCRIPTOR_SIZE);
2387 			memcpy(buf, &xhci_confd, l);
2388 			((usb_config_descriptor_t *)buf)->bDescriptorType =
2389 			    value >> 8;
2390 			buf = (char *)buf + l;
2391 			len -= l;
2392 			l = min(len, USB_INTERFACE_DESCRIPTOR_SIZE);
2393 			totlen += l;
2394 			memcpy(buf, &xhci_ifcd, l);
2395 			buf = (char *)buf + l;
2396 			len -= l;
2397 			l = min(len, USB_ENDPOINT_DESCRIPTOR_SIZE);
2398 			totlen += l;
2399 			memcpy(buf, &xhci_endpd, l);
2400 			break;
2401 		case UDESC_STRING:
2402 			if (len == 0)
2403 				break;
2404 			*(u_int8_t *)buf = 0;
2405 			totlen = 1;
2406 			switch (value & 0xff) {
2407 			case 0: /* Language table */
2408 				totlen = usbd_str(buf, len, "\001");
2409 				break;
2410 			case 1: /* Vendor */
2411 				totlen = usbd_str(buf, len, sc->sc_vendor);
2412 				break;
2413 			case 2: /* Product */
2414 				totlen = usbd_str(buf, len, "xHCI root hub");
2415 				break;
2416 			}
2417 			break;
2418 		default:
2419 			err = USBD_IOERROR;
2420 			goto ret;
2421 		}
2422 		break;
2423 	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
2424 		if (len > 0) {
2425 			*(uint8_t *)buf = 0;
2426 			totlen = 1;
2427 		}
2428 		break;
2429 	case C(UR_GET_STATUS, UT_READ_DEVICE):
2430 		if (len > 1) {
2431 			USETW(((usb_status_t *)buf)->wStatus,UDS_SELF_POWERED);
2432 			totlen = 2;
2433 		}
2434 		break;
2435 	case C(UR_GET_STATUS, UT_READ_INTERFACE):
2436 	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
2437 		if (len > 1) {
2438 			USETW(((usb_status_t *)buf)->wStatus, 0);
2439 			totlen = 2;
2440 		}
2441 		break;
2442 	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
2443 		if (value >= USB_MAX_DEVICES) {
2444 			err = USBD_IOERROR;
2445 			goto ret;
2446 		}
2447 		break;
2448 	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
2449 		if (value != 0 && value != 1) {
2450 			err = USBD_IOERROR;
2451 			goto ret;
2452 		}
2453 		sc->sc_conf = value;
2454 		break;
2455 	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
2456 		break;
2457 	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
2458 	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
2459 	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
2460 		err = USBD_IOERROR;
2461 		goto ret;
2462 	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
2463 		break;
2464 	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
2465 		break;
2466 	/* Hub requests */
2467 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
2468 		break;
2469 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
2470 		DPRINTFN(8, ("xhci_root_ctrl_start: UR_CLEAR_PORT_FEATURE "
2471 		    "port=%d feature=%d\n", index, value));
2472 		if (index < 1 || index > sc->sc_noport) {
2473 			err = USBD_IOERROR;
2474 			goto ret;
2475 		}
2476 		port = XHCI_PORTSC(index);
2477 		v = XOREAD4(sc, port) & ~XHCI_PS_CLEAR;
2478 		switch (value) {
2479 		case UHF_PORT_ENABLE:
2480 			XOWRITE4(sc, port, v | XHCI_PS_PED);
2481 			break;
2482 		case UHF_PORT_SUSPEND:
2483 			/* TODO */
2484 			break;
2485 		case UHF_PORT_POWER:
2486 			XOWRITE4(sc, port, v & ~XHCI_PS_PP);
2487 			break;
2488 		case UHF_PORT_INDICATOR:
2489 			XOWRITE4(sc, port, v & ~XHCI_PS_SET_PIC(3));
2490 			break;
2491 		case UHF_C_PORT_CONNECTION:
2492 			XOWRITE4(sc, port, v | XHCI_PS_CSC);
2493 			break;
2494 		case UHF_C_PORT_ENABLE:
2495 			XOWRITE4(sc, port, v | XHCI_PS_PEC);
2496 			break;
2497 		case UHF_C_PORT_SUSPEND:
2498 		case UHF_C_PORT_LINK_STATE:
2499 			XOWRITE4(sc, port, v | XHCI_PS_PLC);
2500 			break;
2501 		case UHF_C_PORT_OVER_CURRENT:
2502 			XOWRITE4(sc, port, v | XHCI_PS_OCC);
2503 			break;
2504 		case UHF_C_PORT_RESET:
2505 			XOWRITE4(sc, port, v | XHCI_PS_PRC);
2506 			break;
2507 		case UHF_C_BH_PORT_RESET:
2508 			XOWRITE4(sc, port, v | XHCI_PS_WRC);
2509 			break;
2510 		default:
2511 			err = USBD_IOERROR;
2512 			goto ret;
2513 		}
2514 		break;
2515 
2516 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
2517 		if (len == 0)
2518 			break;
2519 		if ((value & 0xff) != 0) {
2520 			err = USBD_IOERROR;
2521 			goto ret;
2522 		}
2523 		v = XREAD4(sc, XHCI_HCCPARAMS);
2524 		hubd = xhci_hubd;
2525 		hubd.bNbrPorts = sc->sc_noport;
2526 		USETW(hubd.wHubCharacteristics,
2527 		    (XHCI_HCC_PPC(v) ? UHD_PWR_INDIVIDUAL : UHD_PWR_GANGED) |
2528 		    (XHCI_HCC_PIND(v) ? UHD_PORT_IND : 0));
2529 		hubd.bPwrOn2PwrGood = 10; /* xHCI section 5.4.9 */
2530 		for (i = 1; i <= sc->sc_noport; i++) {
2531 			v = XOREAD4(sc, XHCI_PORTSC(i));
2532 			if (v & XHCI_PS_DR)
2533 				hubd.DeviceRemovable[i / 8] |= 1U << (i % 8);
2534 		}
2535 		hubd.bDescLength = USB_HUB_DESCRIPTOR_SIZE + i;
2536 		l = min(len, hubd.bDescLength);
2537 		totlen = l;
2538 		memcpy(buf, &hubd, l);
2539 		break;
2540 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
2541 		if (len != 16) {
2542 			err = USBD_IOERROR;
2543 			goto ret;
2544 		}
2545 		memset(buf, 0, len);
2546 		totlen = len;
2547 		break;
2548 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
2549 		DPRINTFN(8,("xhci_root_ctrl_start: get port status i=%d\n",
2550 		    index));
2551 		if (index < 1 || index > sc->sc_noport) {
2552 			err = USBD_IOERROR;
2553 			goto ret;
2554 		}
2555 		if (len != 4) {
2556 			err = USBD_IOERROR;
2557 			goto ret;
2558 		}
2559 		v = XOREAD4(sc, XHCI_PORTSC(index));
2560 		DPRINTFN(8,("xhci_root_ctrl_start: port status=0x%04x\n", v));
2561 		i = UPS_PORT_LS_SET(XHCI_PS_GET_PLS(v));
2562 		switch (XHCI_PS_SPEED(v)) {
2563 		case XHCI_SPEED_FULL:
2564 			i |= UPS_FULL_SPEED;
2565 			break;
2566 		case XHCI_SPEED_LOW:
2567 			i |= UPS_LOW_SPEED;
2568 			break;
2569 		case XHCI_SPEED_HIGH:
2570 			i |= UPS_HIGH_SPEED;
2571 			break;
2572 		case XHCI_SPEED_SUPER:
2573 		default:
2574 			break;
2575 		}
2576 		if (v & XHCI_PS_CCS)	i |= UPS_CURRENT_CONNECT_STATUS;
2577 		if (v & XHCI_PS_PED)	i |= UPS_PORT_ENABLED;
2578 		if (v & XHCI_PS_OCA)	i |= UPS_OVERCURRENT_INDICATOR;
2579 		if (v & XHCI_PS_PR)	i |= UPS_RESET;
2580 		if (v & XHCI_PS_PP)	{
2581 			if (XHCI_PS_SPEED(v) >= XHCI_SPEED_FULL &&
2582 			    XHCI_PS_SPEED(v) <= XHCI_SPEED_HIGH)
2583 				i |= UPS_PORT_POWER;
2584 			else
2585 				i |= UPS_PORT_POWER_SS;
2586 		}
2587 		USETW(ps.wPortStatus, i);
2588 		i = 0;
2589 		if (v & XHCI_PS_CSC)    i |= UPS_C_CONNECT_STATUS;
2590 		if (v & XHCI_PS_PEC)    i |= UPS_C_PORT_ENABLED;
2591 		if (v & XHCI_PS_OCC)    i |= UPS_C_OVERCURRENT_INDICATOR;
2592 		if (v & XHCI_PS_PRC)	i |= UPS_C_PORT_RESET;
2593 		if (v & XHCI_PS_WRC)	i |= UPS_C_BH_PORT_RESET;
2594 		if (v & XHCI_PS_PLC)	i |= UPS_C_PORT_LINK_STATE;
2595 		if (v & XHCI_PS_CEC)	i |= UPS_C_PORT_CONFIG_ERROR;
2596 		USETW(ps.wPortChange, i);
2597 		l = min(len, sizeof ps);
2598 		memcpy(buf, &ps, l);
2599 		totlen = l;
2600 		break;
2601 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
2602 		err = USBD_IOERROR;
2603 		goto ret;
2604 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
2605 		break;
2606 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
2607 
2608 		i = index >> 8;
2609 		index &= 0x00ff;
2610 
2611 		if (index < 1 || index > sc->sc_noport) {
2612 			err = USBD_IOERROR;
2613 			goto ret;
2614 		}
2615 		port = XHCI_PORTSC(index);
2616 		v = XOREAD4(sc, port) & ~XHCI_PS_CLEAR;
2617 
2618 		switch (value) {
2619 		case UHF_PORT_ENABLE:
2620 			XOWRITE4(sc, port, v | XHCI_PS_PED);
2621 			break;
2622 		case UHF_PORT_SUSPEND:
2623 			DPRINTFN(6, ("suspend port %u (LPM=%u)\n", index, i));
2624 			if (XHCI_PS_SPEED(v) == XHCI_SPEED_SUPER) {
2625 				err = USBD_IOERROR;
2626 				goto ret;
2627 			}
2628 			XOWRITE4(sc, port, v |
2629 			    XHCI_PS_SET_PLS(i ? 2 /* LPM */ : 3) | XHCI_PS_LWS);
2630 			break;
2631 		case UHF_PORT_RESET:
2632 			DPRINTFN(6, ("reset port %d\n", index));
2633 			XOWRITE4(sc, port, v | XHCI_PS_PR);
2634 			break;
2635 		case UHF_PORT_POWER:
2636 			DPRINTFN(3, ("set port power %d\n", index));
2637 			XOWRITE4(sc, port, v | XHCI_PS_PP);
2638 			break;
2639 		case UHF_PORT_INDICATOR:
2640 			DPRINTFN(3, ("set port indicator %d\n", index));
2641 
2642 			v &= ~XHCI_PS_SET_PIC(3);
2643 			v |= XHCI_PS_SET_PIC(1);
2644 
2645 			XOWRITE4(sc, port, v);
2646 			break;
2647 		case UHF_C_PORT_RESET:
2648 			XOWRITE4(sc, port, v | XHCI_PS_PRC);
2649 			break;
2650 		case UHF_C_BH_PORT_RESET:
2651 			XOWRITE4(sc, port, v | XHCI_PS_WRC);
2652 			break;
2653 		default:
2654 			err = USBD_IOERROR;
2655 			goto ret;
2656 		}
2657 		break;
2658 	case C(UR_CLEAR_TT_BUFFER, UT_WRITE_CLASS_OTHER):
2659 	case C(UR_RESET_TT, UT_WRITE_CLASS_OTHER):
2660 	case C(UR_GET_TT_STATE, UT_READ_CLASS_OTHER):
2661 	case C(UR_STOP_TT, UT_WRITE_CLASS_OTHER):
2662 		break;
2663 	default:
2664 		err = USBD_IOERROR;
2665 		goto ret;
2666 	}
2667 	xfer->actlen = totlen;
2668 	err = USBD_NORMAL_COMPLETION;
2669 ret:
2670 	xfer->status = err;
2671 	s = splusb();
2672 	usb_transfer_complete(xfer);
2673 	splx(s);
2674 	return (err);
2675 }
2676 
2677 
2678 void
2679 xhci_noop(struct usbd_xfer *xfer)
2680 {
2681 }
2682 
2683 
2684 usbd_status
2685 xhci_root_intr_transfer(struct usbd_xfer *xfer)
2686 {
2687 	usbd_status err;
2688 
2689 	err = usb_insert_transfer(xfer);
2690 	if (err)
2691 		return (err);
2692 
2693 	return (xhci_root_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2694 }
2695 
2696 usbd_status
2697 xhci_root_intr_start(struct usbd_xfer *xfer)
2698 {
2699 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
2700 
2701 	if (sc->sc_bus.dying)
2702 		return (USBD_IOERROR);
2703 
2704 	sc->sc_intrxfer = xfer;
2705 
2706 	return (USBD_IN_PROGRESS);
2707 }
2708 
2709 void
2710 xhci_root_intr_abort(struct usbd_xfer *xfer)
2711 {
2712 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
2713 	int s;
2714 
2715 	sc->sc_intrxfer = NULL;
2716 
2717 	xfer->status = USBD_CANCELLED;
2718 	s = splusb();
2719 	usb_transfer_complete(xfer);
2720 	splx(s);
2721 }
2722 
2723 void
2724 xhci_root_intr_done(struct usbd_xfer *xfer)
2725 {
2726 }
2727 
2728 /*
2729  * Number of packets remaining in the TD after the corresponding TRB.
2730  *
2731  * Section 4.11.2.4 of xHCI specification r1.1.
2732  */
2733 static inline uint32_t
2734 xhci_xfer_tdsize(struct usbd_xfer *xfer, uint32_t remain, uint32_t len)
2735 {
2736 	uint32_t npkt, mps = UGETW(xfer->pipe->endpoint->edesc->wMaxPacketSize);
2737 
2738 	if (len == 0)
2739 		return XHCI_TRB_TDREM(0);
2740 
2741 	npkt = howmany(remain - len, UE_GET_SIZE(mps));
2742 	if (npkt > 31)
2743 		npkt = 31;
2744 
2745 	return XHCI_TRB_TDREM(npkt);
2746 }
2747 
2748 /*
2749  * Transfer Burst Count (TBC) and Transfer Last Burst Packet Count (TLBPC).
2750  *
2751  * Section 4.11.2.3  of xHCI specification r1.1.
2752  */
2753 static inline uint32_t
2754 xhci_xfer_tbc(struct usbd_xfer *xfer, uint32_t len, uint32_t *tlbpc)
2755 {
2756 	uint32_t mps = UGETW(xfer->pipe->endpoint->edesc->wMaxPacketSize);
2757 	uint32_t maxb, tdpc, residue, tbc;
2758 
2759 	/* Transfer Descriptor Packet Count, section 4.14.1. */
2760 	tdpc = howmany(len, UE_GET_SIZE(mps));
2761 	if (tdpc == 0)
2762 		tdpc = 1;
2763 
2764 	/* Transfer Burst Count */
2765 	maxb = xhci_pipe_maxburst(xfer->pipe);
2766 	tbc = howmany(tdpc, maxb + 1) - 1;
2767 
2768 	/* Transfer Last Burst Packet Count */
2769 	if (xfer->device->speed == USB_SPEED_SUPER) {
2770 		residue = tdpc % (maxb + 1);
2771 		if (residue == 0)
2772 			*tlbpc = maxb;
2773 		else
2774 			*tlbpc = residue - 1;
2775 	} else {
2776 		*tlbpc = tdpc - 1;
2777 	}
2778 
2779 	return (tbc);
2780 }
2781 
2782 usbd_status
2783 xhci_device_ctrl_transfer(struct usbd_xfer *xfer)
2784 {
2785 	usbd_status err;
2786 
2787 	err = usb_insert_transfer(xfer);
2788 	if (err)
2789 		return (err);
2790 
2791 	return (xhci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2792 }
2793 
2794 usbd_status
2795 xhci_device_ctrl_start(struct usbd_xfer *xfer)
2796 {
2797 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
2798 	struct xhci_pipe *xp = (struct xhci_pipe *)xfer->pipe;
2799 	struct xhci_trb *trb0, *trb;
2800 	uint32_t flags, len = UGETW(xfer->request.wLength);
2801 	uint8_t toggle;
2802 	int s;
2803 
2804 	KASSERT(xfer->rqflags & URQ_REQUEST);
2805 
2806 	if (sc->sc_bus.dying || xp->halted)
2807 		return (USBD_IOERROR);
2808 
2809 	if (xp->free_trbs < 3)
2810 		return (USBD_NOMEM);
2811 
2812 	/* We'll toggle the setup TRB once we're finished with the stages. */
2813 	trb0 = xhci_xfer_get_trb(sc, xfer, &toggle, 0);
2814 
2815 	flags = XHCI_TRB_TYPE_SETUP | XHCI_TRB_IDT | (toggle ^ 1);
2816 	if (len != 0) {
2817 		if (usbd_xfer_isread(xfer))
2818 			flags |= XHCI_TRB_TRT_IN;
2819 		else
2820 			flags |= XHCI_TRB_TRT_OUT;
2821 	}
2822 
2823 	memcpy(&trb0->trb_paddr, &xfer->request, sizeof(trb0->trb_paddr));
2824 	trb0->trb_status = htole32(XHCI_TRB_INTR(0) | XHCI_TRB_LEN(8));
2825 	trb0->trb_flags = htole32(flags);
2826 	bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2827 	    TRBOFF(&xp->ring, trb0), sizeof(struct xhci_trb),
2828 	    BUS_DMASYNC_PREWRITE);
2829 
2830 	/* Data TRB */
2831 	if (len != 0) {
2832 		trb = xhci_xfer_get_trb(sc, xfer, &toggle, 0);
2833 
2834 		flags = XHCI_TRB_TYPE_DATA | toggle;
2835 		if (usbd_xfer_isread(xfer))
2836 			flags |= XHCI_TRB_DIR_IN | XHCI_TRB_ISP;
2837 
2838 		trb->trb_paddr = htole64(DMAADDR(&xfer->dmabuf, 0));
2839 		trb->trb_status = htole32(
2840 		    XHCI_TRB_INTR(0) | XHCI_TRB_LEN(len) |
2841 		    xhci_xfer_tdsize(xfer, len, len)
2842 		);
2843 		trb->trb_flags = htole32(flags);
2844 
2845 		bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2846 		    TRBOFF(&xp->ring, trb), sizeof(struct xhci_trb),
2847 		    BUS_DMASYNC_PREWRITE);
2848 	}
2849 
2850 	/* Status TRB */
2851 	trb = xhci_xfer_get_trb(sc, xfer, &toggle, 1);
2852 
2853 	flags = XHCI_TRB_TYPE_STATUS | XHCI_TRB_IOC | toggle;
2854 	if (len == 0 || !usbd_xfer_isread(xfer))
2855 		flags |= XHCI_TRB_DIR_IN;
2856 
2857 	trb->trb_paddr = 0;
2858 	trb->trb_status = htole32(XHCI_TRB_INTR(0));
2859 	trb->trb_flags = htole32(flags);
2860 
2861 	bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2862 	    TRBOFF(&xp->ring, trb), sizeof(struct xhci_trb),
2863 	    BUS_DMASYNC_PREWRITE);
2864 
2865 	/* Setup TRB */
2866 	trb0->trb_flags ^= htole32(XHCI_TRB_CYCLE);
2867 	bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2868 	    TRBOFF(&xp->ring, trb0), sizeof(struct xhci_trb),
2869 	    BUS_DMASYNC_PREWRITE);
2870 
2871 	s = splusb();
2872 	XDWRITE4(sc, XHCI_DOORBELL(xp->slot), xp->dci);
2873 
2874 	xfer->status = USBD_IN_PROGRESS;
2875 	if (xfer->timeout && !sc->sc_bus.use_polling) {
2876 		timeout_del(&xfer->timeout_handle);
2877 		timeout_set(&xfer->timeout_handle, xhci_timeout, xfer);
2878 		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
2879 	}
2880 	splx(s);
2881 
2882 	return (USBD_IN_PROGRESS);
2883 }
2884 
2885 void
2886 xhci_device_ctrl_abort(struct usbd_xfer *xfer)
2887 {
2888 	xhci_abort_xfer(xfer, USBD_CANCELLED);
2889 }
2890 
2891 usbd_status
2892 xhci_device_generic_transfer(struct usbd_xfer *xfer)
2893 {
2894 	usbd_status err;
2895 
2896 	err = usb_insert_transfer(xfer);
2897 	if (err)
2898 		return (err);
2899 
2900 	return (xhci_device_generic_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2901 }
2902 
2903 usbd_status
2904 xhci_device_generic_start(struct usbd_xfer *xfer)
2905 {
2906 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
2907 	struct xhci_pipe *xp = (struct xhci_pipe *)xfer->pipe;
2908 	struct xhci_trb *trb0, *trb;
2909 	uint32_t len, remain, flags;
2910 	uint32_t mps = UGETW(xfer->pipe->endpoint->edesc->wMaxPacketSize);
2911 	uint64_t paddr = DMAADDR(&xfer->dmabuf, 0);
2912 	uint8_t toggle;
2913 	int s, i, ntrb, zerotd = 0;
2914 
2915 	KASSERT(!(xfer->rqflags & URQ_REQUEST));
2916 
2917 	if (sc->sc_bus.dying || xp->halted)
2918 		return (USBD_IOERROR);
2919 
2920 	/* How many TRBs do we need for this transfer? */
2921 	ntrb = howmany(xfer->length, XHCI_TRB_MAXSIZE);
2922 
2923 	/* If the buffer crosses a 64k boundary, we need one more. */
2924 	len = XHCI_TRB_MAXSIZE - (paddr & (XHCI_TRB_MAXSIZE - 1));
2925 	if (len < xfer->length)
2926 		ntrb = howmany(xfer->length - len, XHCI_TRB_MAXSIZE) + 1;
2927 	else
2928 		len = xfer->length;
2929 
2930 	/* If we need to append a zero length packet, we need one more. */
2931 	if ((xfer->flags & USBD_FORCE_SHORT_XFER || xfer->length == 0) &&
2932 	    (xfer->length % UE_GET_SIZE(mps) == 0))
2933 		zerotd = 1;
2934 
2935 	if (xp->free_trbs < (ntrb + zerotd))
2936 		return (USBD_NOMEM);
2937 
2938 	/* We'll toggle the first TRB once we're finished with the chain. */
2939 	trb0 = xhci_xfer_get_trb(sc, xfer, &toggle, (ntrb == 1));
2940 	flags = XHCI_TRB_TYPE_NORMAL | (toggle ^ 1);
2941 	if (usbd_xfer_isread(xfer))
2942 		flags |= XHCI_TRB_ISP;
2943 	flags |= (ntrb == 1) ? XHCI_TRB_IOC : XHCI_TRB_CHAIN;
2944 
2945 	trb0->trb_paddr = htole64(DMAADDR(&xfer->dmabuf, 0));
2946 	trb0->trb_status = htole32(
2947 	    XHCI_TRB_INTR(0) | XHCI_TRB_LEN(len) |
2948 	    xhci_xfer_tdsize(xfer, xfer->length, len)
2949 	);
2950 	trb0->trb_flags = htole32(flags);
2951 	bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2952 	    TRBOFF(&xp->ring, trb0), sizeof(struct xhci_trb),
2953 	    BUS_DMASYNC_PREWRITE);
2954 
2955 	remain = xfer->length - len;
2956 	paddr += len;
2957 
2958 	/* Chain more TRBs if needed. */
2959 	for (i = ntrb - 1; i > 0; i--) {
2960 		len = min(remain, XHCI_TRB_MAXSIZE);
2961 
2962 		/* Next (or Last) TRB. */
2963 		trb = xhci_xfer_get_trb(sc, xfer, &toggle, (i == 1));
2964 		flags = XHCI_TRB_TYPE_NORMAL | toggle;
2965 		if (usbd_xfer_isread(xfer))
2966 			flags |= XHCI_TRB_ISP;
2967 		flags |= (i == 1) ? XHCI_TRB_IOC : XHCI_TRB_CHAIN;
2968 
2969 		trb->trb_paddr = htole64(paddr);
2970 		trb->trb_status = htole32(
2971 		    XHCI_TRB_INTR(0) | XHCI_TRB_LEN(len) |
2972 		    xhci_xfer_tdsize(xfer, remain, len)
2973 		);
2974 		trb->trb_flags = htole32(flags);
2975 
2976 		bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2977 		    TRBOFF(&xp->ring, trb), sizeof(struct xhci_trb),
2978 		    BUS_DMASYNC_PREWRITE);
2979 
2980 		remain -= len;
2981 		paddr += len;
2982 	}
2983 
2984 	/* Do we need to issue a zero length transfer? */
2985 	if (zerotd == 1) {
2986 		trb = xhci_xfer_get_trb(sc, xfer, &toggle, -1);
2987 		trb->trb_paddr = 0;
2988 		trb->trb_status = 0;
2989 		trb->trb_flags = htole32(XHCI_TRB_TYPE_NORMAL | XHCI_TRB_IOC | toggle);
2990 		bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2991 		    TRBOFF(&xp->ring, trb), sizeof(struct xhci_trb),
2992 		    BUS_DMASYNC_PREWRITE);
2993 	}
2994 
2995 	/* First TRB. */
2996 	trb0->trb_flags ^= htole32(XHCI_TRB_CYCLE);
2997 	bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
2998 	    TRBOFF(&xp->ring, trb0), sizeof(struct xhci_trb),
2999 	    BUS_DMASYNC_PREWRITE);
3000 
3001 	s = splusb();
3002 	XDWRITE4(sc, XHCI_DOORBELL(xp->slot), xp->dci);
3003 
3004 	xfer->status = USBD_IN_PROGRESS;
3005 	if (xfer->timeout && !sc->sc_bus.use_polling) {
3006 		timeout_del(&xfer->timeout_handle);
3007 		timeout_set(&xfer->timeout_handle, xhci_timeout, xfer);
3008 		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
3009 	}
3010 	splx(s);
3011 
3012 	return (USBD_IN_PROGRESS);
3013 }
3014 
3015 void
3016 xhci_device_generic_done(struct usbd_xfer *xfer)
3017 {
3018 	/* Only happens with interrupt transfers. */
3019 	if (xfer->pipe->repeat) {
3020 		xfer->actlen = 0;
3021 		xhci_device_generic_start(xfer);
3022 	}
3023 }
3024 
3025 void
3026 xhci_device_generic_abort(struct usbd_xfer *xfer)
3027 {
3028 	KASSERT(!xfer->pipe->repeat || xfer->pipe->intrxfer == xfer);
3029 
3030 	xhci_abort_xfer(xfer, USBD_CANCELLED);
3031 }
3032 
3033 usbd_status
3034 xhci_device_isoc_transfer(struct usbd_xfer *xfer)
3035 {
3036 	usbd_status err;
3037 
3038 	err = usb_insert_transfer(xfer);
3039 	if (err && err != USBD_IN_PROGRESS)
3040 		return (err);
3041 
3042 	return (xhci_device_isoc_start(xfer));
3043 }
3044 
3045 usbd_status
3046 xhci_device_isoc_start(struct usbd_xfer *xfer)
3047 {
3048 	struct xhci_softc *sc = (struct xhci_softc *)xfer->device->bus;
3049 	struct xhci_pipe *xp = (struct xhci_pipe *)xfer->pipe;
3050 	struct xhci_xfer *xx = (struct xhci_xfer *)xfer;
3051 	struct xhci_trb *trb0, *trb;
3052 	uint32_t len, remain, flags;
3053 	uint64_t paddr;
3054 	uint32_t tbc, tlbpc;
3055 	int s, i, j, ntrb = xfer->nframes;
3056 	uint8_t toggle;
3057 
3058 	KASSERT(!(xfer->rqflags & URQ_REQUEST));
3059 
3060 	if (sc->sc_bus.dying || xp->halted)
3061 		return (USBD_IOERROR);
3062 
3063 	/* Why would you do that anyway? */
3064 	if (sc->sc_bus.use_polling)
3065 		return (USBD_INVAL);
3066 
3067 	/*
3068 	 * To allow continuous transfers, above we start all transfers
3069 	 * immediately. However, we're still going to get usbd_start_next call
3070 	 * this when another xfer completes. So, check if this is already
3071 	 * in progress or not
3072 	 */
3073 	if (xx->ntrb > 0)
3074 		return (USBD_IN_PROGRESS);
3075 
3076 	paddr = DMAADDR(&xfer->dmabuf, 0);
3077 
3078 	/* How many TRBs do for all Transfers? */
3079 	for (i = 0, ntrb = 0; i < xfer->nframes; i++) {
3080 		/* How many TRBs do we need for this transfer? */
3081 		ntrb += howmany(xfer->frlengths[i], XHCI_TRB_MAXSIZE);
3082 
3083 		/* If the buffer crosses a 64k boundary, we need one more. */
3084 		len = XHCI_TRB_MAXSIZE - (paddr & (XHCI_TRB_MAXSIZE - 1));
3085 		if (len < xfer->frlengths[i])
3086 			ntrb++;
3087 
3088 		paddr += xfer->frlengths[i];
3089 	}
3090 
3091 	if (xp->free_trbs < ntrb)
3092 		return (USBD_NOMEM);
3093 
3094 	paddr = DMAADDR(&xfer->dmabuf, 0);
3095 
3096 	for (i = 0, trb0 = NULL; i < xfer->nframes; i++) {
3097 		/* How many TRBs do we need for this transfer? */
3098 		ntrb = howmany(xfer->frlengths[i], XHCI_TRB_MAXSIZE);
3099 
3100 		/* If the buffer crosses a 64k boundary, we need one more. */
3101 		len = XHCI_TRB_MAXSIZE - (paddr & (XHCI_TRB_MAXSIZE - 1));
3102 		if (len < xfer->frlengths[i])
3103 			ntrb++;
3104 		else
3105 			len = xfer->frlengths[i];
3106 
3107 		KASSERT(ntrb < 3);
3108 
3109 		/*
3110 		 * We'll commit the first TRB once we're finished with the
3111 		 * chain.
3112 		 */
3113 		trb = xhci_xfer_get_trb(sc, xfer, &toggle, (ntrb == 1));
3114 
3115 		DPRINTFN(4, ("%s:%d: ring %p trb0_idx %lu ntrb %d paddr %llx "
3116 		    "len %u\n", __func__, __LINE__,
3117 		    &xp->ring.trbs[0], (trb - &xp->ring.trbs[0]), ntrb, paddr,
3118 		    len));
3119 
3120 		/* Record the first TRB so we can toggle later. */
3121 		if (trb0 == NULL) {
3122 			trb0 = trb;
3123 			toggle ^= 1;
3124 		}
3125 
3126 		flags = XHCI_TRB_TYPE_ISOCH | XHCI_TRB_SIA | toggle;
3127 		if (usbd_xfer_isread(xfer))
3128 			flags |= XHCI_TRB_ISP;
3129 		flags |= (ntrb == 1) ? XHCI_TRB_IOC : XHCI_TRB_CHAIN;
3130 
3131 		tbc = xhci_xfer_tbc(xfer, xfer->frlengths[i], &tlbpc);
3132 		flags |= XHCI_TRB_ISOC_TBC(tbc) | XHCI_TRB_ISOC_TLBPC(tlbpc);
3133 
3134 		trb->trb_paddr = htole64(paddr);
3135 		trb->trb_status = htole32(
3136 		    XHCI_TRB_INTR(0) | XHCI_TRB_LEN(len) |
3137 		    xhci_xfer_tdsize(xfer, xfer->frlengths[i], len)
3138 		);
3139 		trb->trb_flags = htole32(flags);
3140 
3141 		bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
3142 		    TRBOFF(&xp->ring, trb), sizeof(struct xhci_trb),
3143 		    BUS_DMASYNC_PREWRITE);
3144 
3145 		remain = xfer->frlengths[i] - len;
3146 		paddr += len;
3147 
3148 		/* Chain more TRBs if needed. */
3149 		for (j = ntrb - 1; j > 0; j--) {
3150 			len = min(remain, XHCI_TRB_MAXSIZE);
3151 
3152 			/* Next (or Last) TRB. */
3153 			trb = xhci_xfer_get_trb(sc, xfer, &toggle, (j == 1));
3154 			flags = XHCI_TRB_TYPE_NORMAL | toggle;
3155 			if (usbd_xfer_isread(xfer))
3156 				flags |= XHCI_TRB_ISP;
3157 			flags |= (j == 1) ? XHCI_TRB_IOC : XHCI_TRB_CHAIN;
3158 			DPRINTFN(3, ("%s:%d: ring %p trb0_idx %lu ntrb %d "
3159 			    "paddr %llx len %u\n", __func__, __LINE__,
3160 			    &xp->ring.trbs[0], (trb - &xp->ring.trbs[0]), ntrb,
3161 			    paddr, len));
3162 
3163 			trb->trb_paddr = htole64(paddr);
3164 			trb->trb_status = htole32(
3165 			    XHCI_TRB_INTR(0) | XHCI_TRB_LEN(len) |
3166 			    xhci_xfer_tdsize(xfer, remain, len)
3167 			);
3168 			trb->trb_flags = htole32(flags);
3169 
3170 			bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
3171 			    TRBOFF(&xp->ring, trb), sizeof(struct xhci_trb),
3172 			    BUS_DMASYNC_PREWRITE);
3173 
3174 			remain -= len;
3175 			paddr += len;
3176 		}
3177 
3178 		xfer->frlengths[i] = 0;
3179 	}
3180 
3181 	/* First TRB. */
3182 	trb0->trb_flags ^= htole32(XHCI_TRB_CYCLE);
3183 	bus_dmamap_sync(xp->ring.dma.tag, xp->ring.dma.map,
3184 	    TRBOFF(&xp->ring, trb0), sizeof(struct xhci_trb),
3185 	    BUS_DMASYNC_PREWRITE);
3186 
3187 	s = splusb();
3188 	XDWRITE4(sc, XHCI_DOORBELL(xp->slot), xp->dci);
3189 
3190 	xfer->status = USBD_IN_PROGRESS;
3191 
3192 	if (xfer->timeout) {
3193 		timeout_del(&xfer->timeout_handle);
3194 		timeout_set(&xfer->timeout_handle, xhci_timeout, xfer);
3195 		timeout_add_msec(&xfer->timeout_handle, xfer->timeout);
3196 	}
3197 	splx(s);
3198 
3199 	return (USBD_IN_PROGRESS);
3200 }
3201