xref: /netbsd-src/sys/dev/usb/uhci.c (revision 5e4c038a45edbc7d63b7c2daa76e29f88b64a4e3)
1 /*	$NetBSD: uhci.c,v 1.161 2002/06/01 23:51:04 lukem Exp $	*/
2 /*	$FreeBSD: src/sys/dev/usb/uhci.c,v 1.33 1999/11/17 22:33:41 n_hibma Exp $	*/
3 
4 /*
5  * Copyright (c) 1998 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *        This product includes software developed by the NetBSD
23  *        Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 /*
42  * USB Universal Host Controller driver.
43  * Handles e.g. PIIX3 and PIIX4.
44  *
45  * UHCI spec: http://developer.intel.com/design/USB/UHCI11D.htm
46  * USB spec: http://www.usb.org/developers/data/usbspec.zip
47  * PIIXn spec: ftp://download.intel.com/design/intarch/datashts/29055002.pdf
48  *             ftp://download.intel.com/design/intarch/datashts/29056201.pdf
49  */
50 
51 #include <sys/cdefs.h>
52 __KERNEL_RCSID(0, "$NetBSD: uhci.c,v 1.161 2002/06/01 23:51:04 lukem Exp $");
53 
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/kernel.h>
57 #include <sys/malloc.h>
58 #if defined(__NetBSD__) || defined(__OpenBSD__)
59 #include <sys/device.h>
60 #include <sys/select.h>
61 #elif defined(__FreeBSD__)
62 #include <sys/module.h>
63 #include <sys/bus.h>
64 #include <machine/bus_pio.h>
65 #if defined(DIAGNOSTIC) && defined(__i386__)
66 #include <machine/cpu.h>
67 #endif
68 #endif
69 #include <sys/proc.h>
70 #include <sys/queue.h>
71 
72 #include <machine/bus.h>
73 #include <machine/endian.h>
74 
75 #include <dev/usb/usb.h>
76 #include <dev/usb/usbdi.h>
77 #include <dev/usb/usbdivar.h>
78 #include <dev/usb/usb_mem.h>
79 #include <dev/usb/usb_quirks.h>
80 
81 #include <dev/usb/uhcireg.h>
82 #include <dev/usb/uhcivar.h>
83 
84 /* Use bandwidth reclamation for control transfers. Some devices choke on it. */
85 /*#define UHCI_CTL_LOOP */
86 
87 #if defined(__FreeBSD__)
88 #include <machine/clock.h>
89 
90 #define delay(d)		DELAY(d)
91 #endif
92 
93 #define MS_TO_TICKS(ms) ((ms) * hz / 1000)
94 
95 #if defined(__OpenBSD__)
96 struct cfdriver uhci_cd = {
97 	NULL, "uhci", DV_DULL
98 };
99 #endif
100 
101 #ifdef UHCI_DEBUG
102 uhci_softc_t *thesc;
103 #define DPRINTF(x)	if (uhcidebug) printf x
104 #define DPRINTFN(n,x)	if (uhcidebug>(n)) printf x
105 int uhcidebug = 0;
106 int uhcinoloop = 0;
107 #ifndef __NetBSD__
108 #define bitmask_snprintf(q,f,b,l) snprintf((b), (l), "%b", (q), (f))
109 #endif
110 #else
111 #define DPRINTF(x)
112 #define DPRINTFN(n,x)
113 #endif
114 
115 /*
116  * The UHCI controller is little endian, so on big endian machines
117  * the data strored in memory needs to be swapped.
118  */
119 #if defined(__FreeBSD__) || defined(__OpenBSD__)
120 #if BYTE_ORDER == BIG_ENDIAN
121 #define htole32(x) (bswap32(x))
122 #define le32toh(x) (bswap32(x))
123 #else
124 #define htole32(x) (x)
125 #define le32toh(x) (x)
126 #endif
127 #endif
128 
129 struct uhci_pipe {
130 	struct usbd_pipe pipe;
131 	int nexttoggle;
132 
133 	u_char aborting;
134 	usbd_xfer_handle abortstart, abortend;
135 
136 	/* Info needed for different pipe kinds. */
137 	union {
138 		/* Control pipe */
139 		struct {
140 			uhci_soft_qh_t *sqh;
141 			usb_dma_t reqdma;
142 			uhci_soft_td_t *setup, *stat;
143 			u_int length;
144 		} ctl;
145 		/* Interrupt pipe */
146 		struct {
147 			int npoll;
148 			uhci_soft_qh_t **qhs;
149 		} intr;
150 		/* Bulk pipe */
151 		struct {
152 			uhci_soft_qh_t *sqh;
153 			u_int length;
154 			int isread;
155 		} bulk;
156 		/* Iso pipe */
157 		struct iso {
158 			uhci_soft_td_t **stds;
159 			int next, inuse;
160 		} iso;
161 	} u;
162 };
163 
164 Static void		uhci_globalreset(uhci_softc_t *);
165 Static void		uhci_reset(uhci_softc_t *);
166 Static void		uhci_shutdown(void *v);
167 Static void		uhci_power(int, void *);
168 Static usbd_status	uhci_run(uhci_softc_t *, int run);
169 Static uhci_soft_td_t  *uhci_alloc_std(uhci_softc_t *);
170 Static void		uhci_free_std(uhci_softc_t *, uhci_soft_td_t *);
171 Static uhci_soft_qh_t  *uhci_alloc_sqh(uhci_softc_t *);
172 Static void		uhci_free_sqh(uhci_softc_t *, uhci_soft_qh_t *);
173 #if 0
174 Static void		uhci_enter_ctl_q(uhci_softc_t *, uhci_soft_qh_t *,
175 					 uhci_intr_info_t *);
176 Static void		uhci_exit_ctl_q(uhci_softc_t *, uhci_soft_qh_t *);
177 #endif
178 
179 Static void		uhci_free_std_chain(uhci_softc_t *,
180 					    uhci_soft_td_t *, uhci_soft_td_t *);
181 Static usbd_status	uhci_alloc_std_chain(struct uhci_pipe *,
182 			    uhci_softc_t *, int, int, u_int16_t, usb_dma_t *,
183 			    uhci_soft_td_t **, uhci_soft_td_t **);
184 Static void		uhci_poll_hub(void *);
185 Static void		uhci_waitintr(uhci_softc_t *, usbd_xfer_handle);
186 Static void		uhci_check_intr(uhci_softc_t *, uhci_intr_info_t *);
187 Static void		uhci_idone(uhci_intr_info_t *);
188 
189 Static void		uhci_abort_xfer(usbd_xfer_handle, usbd_status status);
190 
191 Static void		uhci_timeout(void *);
192 Static void		uhci_timeout_task(void *);
193 Static void		uhci_add_ls_ctrl(uhci_softc_t *, uhci_soft_qh_t *);
194 Static void		uhci_add_hs_ctrl(uhci_softc_t *, uhci_soft_qh_t *);
195 Static void		uhci_add_bulk(uhci_softc_t *, uhci_soft_qh_t *);
196 Static void		uhci_remove_ls_ctrl(uhci_softc_t *,uhci_soft_qh_t *);
197 Static void		uhci_remove_hs_ctrl(uhci_softc_t *,uhci_soft_qh_t *);
198 Static void		uhci_remove_bulk(uhci_softc_t *,uhci_soft_qh_t *);
199 Static int		uhci_str(usb_string_descriptor_t *, int, char *);
200 Static void		uhci_add_loop(uhci_softc_t *sc);
201 Static void		uhci_rem_loop(uhci_softc_t *sc);
202 
203 Static usbd_status	uhci_setup_isoc(usbd_pipe_handle pipe);
204 Static void		uhci_device_isoc_enter(usbd_xfer_handle);
205 
206 Static usbd_status	uhci_allocm(struct usbd_bus *, usb_dma_t *, u_int32_t);
207 Static void		uhci_freem(struct usbd_bus *, usb_dma_t *);
208 
209 Static usbd_xfer_handle	uhci_allocx(struct usbd_bus *);
210 Static void		uhci_freex(struct usbd_bus *, usbd_xfer_handle);
211 
212 Static usbd_status	uhci_device_ctrl_transfer(usbd_xfer_handle);
213 Static usbd_status	uhci_device_ctrl_start(usbd_xfer_handle);
214 Static void		uhci_device_ctrl_abort(usbd_xfer_handle);
215 Static void		uhci_device_ctrl_close(usbd_pipe_handle);
216 Static void		uhci_device_ctrl_done(usbd_xfer_handle);
217 
218 Static usbd_status	uhci_device_intr_transfer(usbd_xfer_handle);
219 Static usbd_status	uhci_device_intr_start(usbd_xfer_handle);
220 Static void		uhci_device_intr_abort(usbd_xfer_handle);
221 Static void		uhci_device_intr_close(usbd_pipe_handle);
222 Static void		uhci_device_intr_done(usbd_xfer_handle);
223 
224 Static usbd_status	uhci_device_bulk_transfer(usbd_xfer_handle);
225 Static usbd_status	uhci_device_bulk_start(usbd_xfer_handle);
226 Static void		uhci_device_bulk_abort(usbd_xfer_handle);
227 Static void		uhci_device_bulk_close(usbd_pipe_handle);
228 Static void		uhci_device_bulk_done(usbd_xfer_handle);
229 
230 Static usbd_status	uhci_device_isoc_transfer(usbd_xfer_handle);
231 Static usbd_status	uhci_device_isoc_start(usbd_xfer_handle);
232 Static void		uhci_device_isoc_abort(usbd_xfer_handle);
233 Static void		uhci_device_isoc_close(usbd_pipe_handle);
234 Static void		uhci_device_isoc_done(usbd_xfer_handle);
235 
236 Static usbd_status	uhci_root_ctrl_transfer(usbd_xfer_handle);
237 Static usbd_status	uhci_root_ctrl_start(usbd_xfer_handle);
238 Static void		uhci_root_ctrl_abort(usbd_xfer_handle);
239 Static void		uhci_root_ctrl_close(usbd_pipe_handle);
240 Static void		uhci_root_ctrl_done(usbd_xfer_handle);
241 
242 Static usbd_status	uhci_root_intr_transfer(usbd_xfer_handle);
243 Static usbd_status	uhci_root_intr_start(usbd_xfer_handle);
244 Static void		uhci_root_intr_abort(usbd_xfer_handle);
245 Static void		uhci_root_intr_close(usbd_pipe_handle);
246 Static void		uhci_root_intr_done(usbd_xfer_handle);
247 
248 Static usbd_status	uhci_open(usbd_pipe_handle);
249 Static void		uhci_poll(struct usbd_bus *);
250 Static void		uhci_softintr(void *);
251 
252 Static usbd_status	uhci_device_request(usbd_xfer_handle xfer);
253 
254 Static void		uhci_add_intr(uhci_softc_t *, uhci_soft_qh_t *);
255 Static void		uhci_remove_intr(uhci_softc_t *, uhci_soft_qh_t *);
256 Static usbd_status	uhci_device_setintr(uhci_softc_t *sc,
257 			    struct uhci_pipe *pipe, int ival);
258 
259 Static void		uhci_device_clear_toggle(usbd_pipe_handle pipe);
260 Static void		uhci_noop(usbd_pipe_handle pipe);
261 
262 Static __inline__ uhci_soft_qh_t *uhci_find_prev_qh(uhci_soft_qh_t *,
263 						    uhci_soft_qh_t *);
264 
265 #ifdef UHCI_DEBUG
266 Static void		uhci_dump_all(uhci_softc_t *);
267 Static void		uhci_dumpregs(uhci_softc_t *);
268 Static void		uhci_dump_qhs(uhci_soft_qh_t *);
269 Static void		uhci_dump_qh(uhci_soft_qh_t *);
270 Static void		uhci_dump_tds(uhci_soft_td_t *);
271 Static void		uhci_dump_td(uhci_soft_td_t *);
272 Static void		uhci_dump_ii(uhci_intr_info_t *ii);
273 void			uhci_dump(void);
274 #endif
275 
276 #define UBARR(sc) bus_space_barrier((sc)->iot, (sc)->ioh, 0, (sc)->sc_size, \
277 			BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE)
278 #define UWRITE1(sc, r, x) \
279  do { UBARR(sc); bus_space_write_1((sc)->iot, (sc)->ioh, (r), (x)); } while (0)
280 #define UWRITE2(sc, r, x) \
281  do { UBARR(sc); bus_space_write_2((sc)->iot, (sc)->ioh, (r), (x)); } while (0)
282 #define UWRITE4(sc, r, x) \
283  do { UBARR(sc); bus_space_write_4((sc)->iot, (sc)->ioh, (r), (x)); } while (0)
284 #define UREAD1(sc, r) (UBARR(sc), bus_space_read_1((sc)->iot, (sc)->ioh, (r)))
285 #define UREAD2(sc, r) (UBARR(sc), bus_space_read_2((sc)->iot, (sc)->ioh, (r)))
286 #define UREAD4(sc, r) (UBARR(sc), bus_space_read_4((sc)->iot, (sc)->ioh, (r)))
287 
288 #define UHCICMD(sc, cmd) UWRITE2(sc, UHCI_CMD, cmd)
289 #define UHCISTS(sc) UREAD2(sc, UHCI_STS)
290 
291 #define UHCI_RESET_TIMEOUT 100	/* ms, reset timeout */
292 
293 #define UHCI_CURFRAME(sc) (UREAD2(sc, UHCI_FRNUM) & UHCI_FRNUM_MASK)
294 
295 #define UHCI_INTR_ENDPT 1
296 
297 struct usbd_bus_methods uhci_bus_methods = {
298 	uhci_open,
299 	uhci_softintr,
300 	uhci_poll,
301 	uhci_allocm,
302 	uhci_freem,
303 	uhci_allocx,
304 	uhci_freex,
305 };
306 
307 struct usbd_pipe_methods uhci_root_ctrl_methods = {
308 	uhci_root_ctrl_transfer,
309 	uhci_root_ctrl_start,
310 	uhci_root_ctrl_abort,
311 	uhci_root_ctrl_close,
312 	uhci_noop,
313 	uhci_root_ctrl_done,
314 };
315 
316 struct usbd_pipe_methods uhci_root_intr_methods = {
317 	uhci_root_intr_transfer,
318 	uhci_root_intr_start,
319 	uhci_root_intr_abort,
320 	uhci_root_intr_close,
321 	uhci_noop,
322 	uhci_root_intr_done,
323 };
324 
325 struct usbd_pipe_methods uhci_device_ctrl_methods = {
326 	uhci_device_ctrl_transfer,
327 	uhci_device_ctrl_start,
328 	uhci_device_ctrl_abort,
329 	uhci_device_ctrl_close,
330 	uhci_noop,
331 	uhci_device_ctrl_done,
332 };
333 
334 struct usbd_pipe_methods uhci_device_intr_methods = {
335 	uhci_device_intr_transfer,
336 	uhci_device_intr_start,
337 	uhci_device_intr_abort,
338 	uhci_device_intr_close,
339 	uhci_device_clear_toggle,
340 	uhci_device_intr_done,
341 };
342 
343 struct usbd_pipe_methods uhci_device_bulk_methods = {
344 	uhci_device_bulk_transfer,
345 	uhci_device_bulk_start,
346 	uhci_device_bulk_abort,
347 	uhci_device_bulk_close,
348 	uhci_device_clear_toggle,
349 	uhci_device_bulk_done,
350 };
351 
352 struct usbd_pipe_methods uhci_device_isoc_methods = {
353 	uhci_device_isoc_transfer,
354 	uhci_device_isoc_start,
355 	uhci_device_isoc_abort,
356 	uhci_device_isoc_close,
357 	uhci_noop,
358 	uhci_device_isoc_done,
359 };
360 
361 #define uhci_add_intr_info(sc, ii) \
362 	LIST_INSERT_HEAD(&(sc)->sc_intrhead, (ii), list);
363 #define uhci_del_intr_info(ii) \
364 	LIST_REMOVE((ii), list)
365 
366 Static __inline__ uhci_soft_qh_t *
367 uhci_find_prev_qh(uhci_soft_qh_t *pqh, uhci_soft_qh_t *sqh)
368 {
369 	DPRINTFN(15,("uhci_find_prev_qh: pqh=%p sqh=%p\n", pqh, sqh));
370 
371 	for (; pqh->hlink != sqh; pqh = pqh->hlink) {
372 #if defined(DIAGNOSTIC) || defined(UHCI_DEBUG)
373 		if (le32toh(pqh->qh.qh_hlink) & UHCI_PTR_T) {
374 			printf("uhci_find_prev_qh: QH not found\n");
375 			return (NULL);
376 		}
377 #endif
378 	}
379 	return (pqh);
380 }
381 
382 void
383 uhci_globalreset(uhci_softc_t *sc)
384 {
385 	UHCICMD(sc, UHCI_CMD_GRESET);	/* global reset */
386 	usb_delay_ms(&sc->sc_bus, USB_BUS_RESET_DELAY); /* wait a little */
387 	UHCICMD(sc, 0);			/* do nothing */
388 }
389 
390 usbd_status
391 uhci_init(uhci_softc_t *sc)
392 {
393 	usbd_status err;
394 	int i, j;
395 	uhci_soft_qh_t *clsqh, *chsqh, *bsqh, *sqh, *lsqh;
396 	uhci_soft_td_t *std;
397 
398 	DPRINTFN(1,("uhci_init: start\n"));
399 
400 #ifdef UHCI_DEBUG
401 	thesc = sc;
402 
403 	if (uhcidebug > 2)
404 		uhci_dumpregs(sc);
405 #endif
406 
407 	UWRITE2(sc, UHCI_INTR, 0);		/* disable interrupts */
408 	uhci_globalreset(sc);			/* reset the controller */
409 	uhci_reset(sc);
410 
411 	/* Allocate and initialize real frame array. */
412 	err = usb_allocmem(&sc->sc_bus,
413 		  UHCI_FRAMELIST_COUNT * sizeof(uhci_physaddr_t),
414 		  UHCI_FRAMELIST_ALIGN, &sc->sc_dma);
415 	if (err)
416 		return (err);
417 	sc->sc_pframes = KERNADDR(&sc->sc_dma, 0);
418 	UWRITE2(sc, UHCI_FRNUM, 0);		/* set frame number to 0 */
419 	UWRITE4(sc, UHCI_FLBASEADDR, DMAADDR(&sc->sc_dma, 0)); /* set frame list*/
420 
421 	/*
422 	 * Allocate a TD, inactive, that hangs from the last QH.
423 	 * This is to avoid a bug in the PIIX that makes it run berserk
424 	 * otherwise.
425 	 */
426 	std = uhci_alloc_std(sc);
427 	if (std == NULL)
428 		return (USBD_NOMEM);
429 	std->link.std = NULL;
430 	std->td.td_link = htole32(UHCI_PTR_T);
431 	std->td.td_status = htole32(0); /* inactive */
432 	std->td.td_token = htole32(0);
433 	std->td.td_buffer = htole32(0);
434 
435 	/* Allocate the dummy QH marking the end and used for looping the QHs.*/
436 	lsqh = uhci_alloc_sqh(sc);
437 	if (lsqh == NULL)
438 		return (USBD_NOMEM);
439 	lsqh->hlink = NULL;
440 	lsqh->qh.qh_hlink = htole32(UHCI_PTR_T);	/* end of QH chain */
441 	lsqh->elink = std;
442 	lsqh->qh.qh_elink = htole32(std->physaddr | UHCI_PTR_TD);
443 	sc->sc_last_qh = lsqh;
444 
445 	/* Allocate the dummy QH where bulk traffic will be queued. */
446 	bsqh = uhci_alloc_sqh(sc);
447 	if (bsqh == NULL)
448 		return (USBD_NOMEM);
449 	bsqh->hlink = lsqh;
450 	bsqh->qh.qh_hlink = htole32(lsqh->physaddr | UHCI_PTR_QH);
451 	bsqh->elink = NULL;
452 	bsqh->qh.qh_elink = htole32(UHCI_PTR_T);
453 	sc->sc_bulk_start = sc->sc_bulk_end = bsqh;
454 
455 	/* Allocate dummy QH where high speed control traffic will be queued. */
456 	chsqh = uhci_alloc_sqh(sc);
457 	if (chsqh == NULL)
458 		return (USBD_NOMEM);
459 	chsqh->hlink = bsqh;
460 	chsqh->qh.qh_hlink = htole32(bsqh->physaddr | UHCI_PTR_QH);
461 	chsqh->elink = NULL;
462 	chsqh->qh.qh_elink = htole32(UHCI_PTR_T);
463 	sc->sc_hctl_start = sc->sc_hctl_end = chsqh;
464 
465 	/* Allocate dummy QH where control traffic will be queued. */
466 	clsqh = uhci_alloc_sqh(sc);
467 	if (clsqh == NULL)
468 		return (USBD_NOMEM);
469 	clsqh->hlink = bsqh;
470 	clsqh->qh.qh_hlink = htole32(chsqh->physaddr | UHCI_PTR_QH);
471 	clsqh->elink = NULL;
472 	clsqh->qh.qh_elink = htole32(UHCI_PTR_T);
473 	sc->sc_lctl_start = sc->sc_lctl_end = clsqh;
474 
475 	/*
476 	 * Make all (virtual) frame list pointers point to the interrupt
477 	 * queue heads and the interrupt queue heads at the control
478 	 * queue head and point the physical frame list to the virtual.
479 	 */
480 	for(i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
481 		std = uhci_alloc_std(sc);
482 		sqh = uhci_alloc_sqh(sc);
483 		if (std == NULL || sqh == NULL)
484 			return (USBD_NOMEM);
485 		std->link.sqh = sqh;
486 		std->td.td_link = htole32(sqh->physaddr | UHCI_PTR_QH);
487 		std->td.td_status = htole32(UHCI_TD_IOS); /* iso, inactive */
488 		std->td.td_token = htole32(0);
489 		std->td.td_buffer = htole32(0);
490 		sqh->hlink = clsqh;
491 		sqh->qh.qh_hlink = htole32(clsqh->physaddr | UHCI_PTR_QH);
492 		sqh->elink = NULL;
493 		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
494 		sc->sc_vframes[i].htd = std;
495 		sc->sc_vframes[i].etd = std;
496 		sc->sc_vframes[i].hqh = sqh;
497 		sc->sc_vframes[i].eqh = sqh;
498 		for (j = i;
499 		     j < UHCI_FRAMELIST_COUNT;
500 		     j += UHCI_VFRAMELIST_COUNT)
501 			sc->sc_pframes[j] = htole32(std->physaddr);
502 	}
503 
504 	LIST_INIT(&sc->sc_intrhead);
505 
506 	SIMPLEQ_INIT(&sc->sc_free_xfers);
507 
508 	usb_callout_init(sc->sc_poll_handle);
509 
510 	/* Set up the bus struct. */
511 	sc->sc_bus.methods = &uhci_bus_methods;
512 	sc->sc_bus.pipe_size = sizeof(struct uhci_pipe);
513 
514 #if defined(__NetBSD__) || defined(__OpenBSD__)
515 	sc->sc_suspend = PWR_RESUME;
516 	sc->sc_powerhook = powerhook_establish(uhci_power, sc);
517 	sc->sc_shutdownhook = shutdownhook_establish(uhci_shutdown, sc);
518 #endif
519 
520 	DPRINTFN(1,("uhci_init: enabling\n"));
521 	UWRITE2(sc, UHCI_INTR, UHCI_INTR_TOCRCIE | UHCI_INTR_RIE |
522 		UHCI_INTR_IOCE | UHCI_INTR_SPIE);	/* enable interrupts */
523 
524 	UHCICMD(sc, UHCI_CMD_MAXP); /* Assume 64 byte packets at frame end */
525 
526 	return (uhci_run(sc, 1));		/* and here we go... */
527 }
528 
529 #if defined(__NetBSD__) || defined(__OpenBSD__)
530 int
531 uhci_activate(device_ptr_t self, enum devact act)
532 {
533 	struct uhci_softc *sc = (struct uhci_softc *)self;
534 	int rv = 0;
535 
536 	switch (act) {
537 	case DVACT_ACTIVATE:
538 		return (EOPNOTSUPP);
539 		break;
540 
541 	case DVACT_DEACTIVATE:
542 		if (sc->sc_child != NULL)
543 			rv = config_deactivate(sc->sc_child);
544 		break;
545 	}
546 	return (rv);
547 }
548 
549 int
550 uhci_detach(struct uhci_softc *sc, int flags)
551 {
552 	usbd_xfer_handle xfer;
553 	int rv = 0;
554 
555 	if (sc->sc_child != NULL)
556 		rv = config_detach(sc->sc_child, flags);
557 
558 	if (rv != 0)
559 		return (rv);
560 
561 #if defined(__NetBSD__) || defined(__OpenBSD__)
562 	powerhook_disestablish(sc->sc_powerhook);
563 	shutdownhook_disestablish(sc->sc_shutdownhook);
564 #endif
565 
566 	/* Free all xfers associated with this HC. */
567 	for (;;) {
568 		xfer = SIMPLEQ_FIRST(&sc->sc_free_xfers);
569 		if (xfer == NULL)
570 			break;
571 		SIMPLEQ_REMOVE_HEAD(&sc->sc_free_xfers, next);
572 		free(xfer, M_USB);
573 	}
574 
575 	/* XXX free other data structures XXX */
576 
577 	return (rv);
578 }
579 #endif
580 
581 usbd_status
582 uhci_allocm(struct usbd_bus *bus, usb_dma_t *dma, u_int32_t size)
583 {
584 	struct uhci_softc *sc = (struct uhci_softc *)bus;
585 	u_int32_t n;
586 
587 	/*
588 	 * XXX
589 	 * Since we are allocating a buffer we can assume that we will
590 	 * need TDs for it.  Since we don't want to allocate those from
591 	 * an interrupt context, we allocate them here and free them again.
592 	 * This is no guarantee that we'll get the TDs next time...
593 	 */
594 	n = size / 8;
595 	if (n > 16) {
596 		u_int32_t i;
597 		uhci_soft_td_t **stds;
598 		DPRINTF(("uhci_allocm: get %d TDs\n", n));
599 		stds = malloc(sizeof(uhci_soft_td_t *) * n, M_TEMP,
600 		    M_WAITOK|M_ZERO);
601 		for(i=0; i < n; i++)
602 			stds[i] = uhci_alloc_std(sc);
603 		for(i=0; i < n; i++)
604 			if (stds[i] != NULL)
605 				uhci_free_std(sc, stds[i]);
606 		free(stds, M_TEMP);
607 	}
608 
609 	return (usb_allocmem(&sc->sc_bus, size, 0, dma));
610 }
611 
612 void
613 uhci_freem(struct usbd_bus *bus, usb_dma_t *dma)
614 {
615 	usb_freemem(&((struct uhci_softc *)bus)->sc_bus, dma);
616 }
617 
618 usbd_xfer_handle
619 uhci_allocx(struct usbd_bus *bus)
620 {
621 	struct uhci_softc *sc = (struct uhci_softc *)bus;
622 	usbd_xfer_handle xfer;
623 
624 	xfer = SIMPLEQ_FIRST(&sc->sc_free_xfers);
625 	if (xfer != NULL) {
626 		SIMPLEQ_REMOVE_HEAD(&sc->sc_free_xfers, next);
627 #ifdef DIAGNOSTIC
628 		if (xfer->busy_free != XFER_FREE) {
629 			printf("uhci_allocx: xfer=%p not free, 0x%08x\n", xfer,
630 			       xfer->busy_free);
631 		}
632 #endif
633 	} else {
634 		xfer = malloc(sizeof(struct uhci_xfer), M_USB, M_NOWAIT);
635 	}
636 	if (xfer != NULL) {
637 		memset(xfer, 0, sizeof (struct uhci_xfer));
638 		UXFER(xfer)->iinfo.sc = sc;
639 #ifdef DIAGNOSTIC
640 		UXFER(xfer)->iinfo.isdone = 1;
641 		xfer->busy_free = XFER_BUSY;
642 #endif
643 	}
644 	return (xfer);
645 }
646 
647 void
648 uhci_freex(struct usbd_bus *bus, usbd_xfer_handle xfer)
649 {
650 	struct uhci_softc *sc = (struct uhci_softc *)bus;
651 
652 #ifdef DIAGNOSTIC
653 	if (xfer->busy_free != XFER_BUSY) {
654 		printf("uhci_freex: xfer=%p not busy, 0x%08x\n", xfer,
655 		       xfer->busy_free);
656 		return;
657 	}
658 	xfer->busy_free = XFER_FREE;
659 	if (!UXFER(xfer)->iinfo.isdone) {
660 		printf("uhci_freex: !isdone\n");
661 		return;
662 	}
663 #endif
664 	SIMPLEQ_INSERT_HEAD(&sc->sc_free_xfers, xfer, next);
665 }
666 
667 /*
668  * Shut down the controller when the system is going down.
669  */
670 void
671 uhci_shutdown(void *v)
672 {
673 	uhci_softc_t *sc = v;
674 
675 	DPRINTF(("uhci_shutdown: stopping the HC\n"));
676 	uhci_run(sc, 0); /* stop the controller */
677 }
678 
679 /*
680  * Handle suspend/resume.
681  *
682  * We need to switch to polling mode here, because this routine is
683  * called from an interrupt context.  This is all right since we
684  * are almost suspended anyway.
685  */
686 void
687 uhci_power(int why, void *v)
688 {
689 	uhci_softc_t *sc = v;
690 	int cmd;
691 	int s;
692 
693 	s = splhardusb();
694 	cmd = UREAD2(sc, UHCI_CMD);
695 
696 	DPRINTF(("uhci_power: sc=%p, why=%d (was %d), cmd=0x%x\n",
697 		 sc, why, sc->sc_suspend, cmd));
698 
699 	switch (why) {
700 	case PWR_SUSPEND:
701 	case PWR_STANDBY:
702 #ifdef UHCI_DEBUG
703 		if (uhcidebug > 2)
704 			uhci_dumpregs(sc);
705 #endif
706 		if (sc->sc_intr_xfer != NULL)
707 			usb_uncallout(sc->sc_poll_handle, uhci_poll_hub,
708 			    sc->sc_intr_xfer);
709 		sc->sc_bus.use_polling++;
710 		uhci_run(sc, 0); /* stop the controller */
711 
712 		/* save some state if BIOS doesn't */
713 		sc->sc_saved_frnum = UREAD2(sc, UHCI_FRNUM);
714 		sc->sc_saved_sof = UREAD1(sc, UHCI_SOF);
715 
716 		UWRITE2(sc, UHCI_INTR, 0); /* disable intrs */
717 
718 		UHCICMD(sc, cmd | UHCI_CMD_EGSM); /* enter global suspend */
719 		usb_delay_ms(&sc->sc_bus, USB_RESUME_WAIT);
720 		sc->sc_suspend = why;
721 		sc->sc_bus.use_polling--;
722 		DPRINTF(("uhci_power: cmd=0x%x\n", UREAD2(sc, UHCI_CMD)));
723 		break;
724 	case PWR_RESUME:
725 #ifdef DIAGNOSTIC
726 		if (sc->sc_suspend == PWR_RESUME)
727 			printf("uhci_power: weird, resume without suspend.\n");
728 #endif
729 		sc->sc_bus.use_polling++;
730 		sc->sc_suspend = why;
731 		if (cmd & UHCI_CMD_RS)
732 			uhci_run(sc, 0); /* in case BIOS has started it */
733 
734 		/* restore saved state */
735 		UWRITE4(sc, UHCI_FLBASEADDR, DMAADDR(&sc->sc_dma, 0));
736 		UWRITE2(sc, UHCI_FRNUM, sc->sc_saved_frnum);
737 		UWRITE1(sc, UHCI_SOF, sc->sc_saved_sof);
738 
739 		UHCICMD(sc, cmd | UHCI_CMD_FGR); /* force global resume */
740 		usb_delay_ms(&sc->sc_bus, USB_RESUME_DELAY);
741 		UHCICMD(sc, cmd & ~UHCI_CMD_EGSM); /* back to normal */
742 		UWRITE2(sc, UHCI_INTR, UHCI_INTR_TOCRCIE | UHCI_INTR_RIE |
743 			UHCI_INTR_IOCE | UHCI_INTR_SPIE); /* re-enable intrs */
744 		uhci_run(sc, 1); /* and start traffic again */
745 		usb_delay_ms(&sc->sc_bus, USB_RESUME_RECOVERY);
746 		sc->sc_bus.use_polling--;
747 		if (sc->sc_intr_xfer != NULL)
748 			usb_callout(sc->sc_poll_handle, sc->sc_ival,
749 				    uhci_poll_hub, sc->sc_intr_xfer);
750 #ifdef UHCI_DEBUG
751 		if (uhcidebug > 2)
752 			uhci_dumpregs(sc);
753 #endif
754 		break;
755 	case PWR_SOFTSUSPEND:
756 	case PWR_SOFTSTANDBY:
757 	case PWR_SOFTRESUME:
758 		break;
759 	}
760 	splx(s);
761 }
762 
763 #ifdef UHCI_DEBUG
764 Static void
765 uhci_dumpregs(uhci_softc_t *sc)
766 {
767 	DPRINTFN(-1,("%s regs: cmd=%04x, sts=%04x, intr=%04x, frnum=%04x, "
768 		     "flbase=%08x, sof=%04x, portsc1=%04x, portsc2=%04x\n",
769 		     USBDEVNAME(sc->sc_bus.bdev),
770 		     UREAD2(sc, UHCI_CMD),
771 		     UREAD2(sc, UHCI_STS),
772 		     UREAD2(sc, UHCI_INTR),
773 		     UREAD2(sc, UHCI_FRNUM),
774 		     UREAD4(sc, UHCI_FLBASEADDR),
775 		     UREAD1(sc, UHCI_SOF),
776 		     UREAD2(sc, UHCI_PORTSC1),
777 		     UREAD2(sc, UHCI_PORTSC2)));
778 }
779 
780 void
781 uhci_dump_td(uhci_soft_td_t *p)
782 {
783 	char sbuf[128], sbuf2[128];
784 
785 	DPRINTFN(-1,("TD(%p) at %08lx = link=0x%08lx status=0x%08lx "
786 		     "token=0x%08lx buffer=0x%08lx\n",
787 		     p, (long)p->physaddr,
788 		     (long)le32toh(p->td.td_link),
789 		     (long)le32toh(p->td.td_status),
790 		     (long)le32toh(p->td.td_token),
791 		     (long)le32toh(p->td.td_buffer)));
792 
793 	bitmask_snprintf((u_int32_t)le32toh(p->td.td_link), "\20\1T\2Q\3VF",
794 			 sbuf, sizeof(sbuf));
795 	bitmask_snprintf((u_int32_t)le32toh(p->td.td_status),
796 			 "\20\22BITSTUFF\23CRCTO\24NAK\25BABBLE\26DBUFFER\27"
797 			 "STALLED\30ACTIVE\31IOC\32ISO\33LS\36SPD",
798 			 sbuf2, sizeof(sbuf2));
799 
800 	DPRINTFN(-1,("  %s %s,errcnt=%d,actlen=%d pid=%02x,addr=%d,endpt=%d,"
801 		     "D=%d,maxlen=%d\n", sbuf, sbuf2,
802 		     UHCI_TD_GET_ERRCNT(le32toh(p->td.td_status)),
803 		     UHCI_TD_GET_ACTLEN(le32toh(p->td.td_status)),
804 		     UHCI_TD_GET_PID(le32toh(p->td.td_token)),
805 		     UHCI_TD_GET_DEVADDR(le32toh(p->td.td_token)),
806 		     UHCI_TD_GET_ENDPT(le32toh(p->td.td_token)),
807 		     UHCI_TD_GET_DT(le32toh(p->td.td_token)),
808 		     UHCI_TD_GET_MAXLEN(le32toh(p->td.td_token))));
809 }
810 
811 void
812 uhci_dump_qh(uhci_soft_qh_t *sqh)
813 {
814 	DPRINTFN(-1,("QH(%p) at %08x: hlink=%08x elink=%08x\n", sqh,
815 	    (int)sqh->physaddr, le32toh(sqh->qh.qh_hlink),
816 	    le32toh(sqh->qh.qh_elink)));
817 }
818 
819 
820 #if 1
821 void
822 uhci_dump(void)
823 {
824 	uhci_dump_all(thesc);
825 }
826 #endif
827 
828 void
829 uhci_dump_all(uhci_softc_t *sc)
830 {
831 	uhci_dumpregs(sc);
832 	printf("intrs=%d\n", sc->sc_bus.no_intrs);
833 	/*printf("framelist[i].link = %08x\n", sc->sc_framelist[0].link);*/
834 	uhci_dump_qh(sc->sc_lctl_start);
835 }
836 
837 
838 void
839 uhci_dump_qhs(uhci_soft_qh_t *sqh)
840 {
841 	uhci_dump_qh(sqh);
842 
843 	/* uhci_dump_qhs displays all the QHs and TDs from the given QH onwards
844 	 * Traverses sideways first, then down.
845 	 *
846 	 * QH1
847 	 * QH2
848 	 * No QH
849 	 * TD2.1
850 	 * TD2.2
851 	 * TD1.1
852 	 * etc.
853 	 *
854 	 * TD2.x being the TDs queued at QH2 and QH1 being referenced from QH1.
855 	 */
856 
857 
858 	if (sqh->hlink != NULL && !(le32toh(sqh->qh.qh_hlink) & UHCI_PTR_T))
859 		uhci_dump_qhs(sqh->hlink);
860 	else
861 		DPRINTF(("No QH\n"));
862 
863 	if (sqh->elink != NULL && !(le32toh(sqh->qh.qh_elink) & UHCI_PTR_T))
864 		uhci_dump_tds(sqh->elink);
865 	else
866 		DPRINTF(("No TD\n"));
867 }
868 
869 void
870 uhci_dump_tds(uhci_soft_td_t *std)
871 {
872 	uhci_soft_td_t *td;
873 
874 	for(td = std; td != NULL; td = td->link.std) {
875 		uhci_dump_td(td);
876 
877 		/* Check whether the link pointer in this TD marks
878 		 * the link pointer as end of queue. This avoids
879 		 * printing the free list in case the queue/TD has
880 		 * already been moved there (seatbelt).
881 		 */
882 		if (le32toh(td->td.td_link) & UHCI_PTR_T ||
883 		    le32toh(td->td.td_link) == 0)
884 			break;
885 	}
886 }
887 
888 Static void
889 uhci_dump_ii(uhci_intr_info_t *ii)
890 {
891 	usbd_pipe_handle pipe;
892 	usb_endpoint_descriptor_t *ed;
893 	usbd_device_handle dev;
894 
895 #ifdef DIAGNOSTIC
896 #define DONE ii->isdone
897 #else
898 #define DONE 0
899 #endif
900         if (ii == NULL) {
901                 printf("ii NULL\n");
902                 return;
903         }
904         if (ii->xfer == NULL) {
905 		printf("ii %p: done=%d xfer=NULL\n",
906 		       ii, DONE);
907                 return;
908         }
909         pipe = ii->xfer->pipe;
910         if (pipe == NULL) {
911 		printf("ii %p: done=%d xfer=%p pipe=NULL\n",
912 		       ii, DONE, ii->xfer);
913                 return;
914 	}
915         if (pipe->endpoint == NULL) {
916 		printf("ii %p: done=%d xfer=%p pipe=%p pipe->endpoint=NULL\n",
917 		       ii, DONE, ii->xfer, pipe);
918                 return;
919 	}
920         if (pipe->device == NULL) {
921 		printf("ii %p: done=%d xfer=%p pipe=%p pipe->device=NULL\n",
922 		       ii, DONE, ii->xfer, pipe);
923                 return;
924 	}
925         ed = pipe->endpoint->edesc;
926         dev = pipe->device;
927 	printf("ii %p: done=%d xfer=%p dev=%p vid=0x%04x pid=0x%04x addr=%d pipe=%p ep=0x%02x attr=0x%02x\n",
928 	       ii, DONE, ii->xfer, dev,
929 	       UGETW(dev->ddesc.idVendor),
930 	       UGETW(dev->ddesc.idProduct),
931 	       dev->address, pipe,
932 	       ed->bEndpointAddress, ed->bmAttributes);
933 #undef DONE
934 }
935 
936 void uhci_dump_iis(struct uhci_softc *sc);
937 void
938 uhci_dump_iis(struct uhci_softc *sc)
939 {
940 	uhci_intr_info_t *ii;
941 
942 	printf("intr_info list:\n");
943 	for (ii = LIST_FIRST(&sc->sc_intrhead); ii; ii = LIST_NEXT(ii, list))
944 		uhci_dump_ii(ii);
945 }
946 
947 void iidump(void);
948 void iidump(void) { uhci_dump_iis(thesc); }
949 
950 #endif
951 
952 /*
953  * This routine is executed periodically and simulates interrupts
954  * from the root controller interrupt pipe for port status change.
955  */
956 void
957 uhci_poll_hub(void *addr)
958 {
959 	usbd_xfer_handle xfer = addr;
960 	usbd_pipe_handle pipe = xfer->pipe;
961 	uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
962 	int s;
963 	u_char *p;
964 
965 	DPRINTFN(20, ("uhci_poll_hub\n"));
966 
967 	usb_callout(sc->sc_poll_handle, sc->sc_ival, uhci_poll_hub, xfer);
968 
969 	p = KERNADDR(&xfer->dmabuf, 0);
970 	p[0] = 0;
971 	if (UREAD2(sc, UHCI_PORTSC1) & (UHCI_PORTSC_CSC|UHCI_PORTSC_OCIC))
972 		p[0] |= 1<<1;
973 	if (UREAD2(sc, UHCI_PORTSC2) & (UHCI_PORTSC_CSC|UHCI_PORTSC_OCIC))
974 		p[0] |= 1<<2;
975 	if (p[0] == 0)
976 		/* No change, try again in a while */
977 		return;
978 
979 	xfer->actlen = 1;
980 	xfer->status = USBD_NORMAL_COMPLETION;
981 	s = splusb();
982 	xfer->device->bus->intr_context++;
983 	usb_transfer_complete(xfer);
984 	xfer->device->bus->intr_context--;
985 	splx(s);
986 }
987 
988 void
989 uhci_root_intr_done(usbd_xfer_handle xfer)
990 {
991 }
992 
993 void
994 uhci_root_ctrl_done(usbd_xfer_handle xfer)
995 {
996 }
997 
998 /*
999  * Let the last QH loop back to the high speed control transfer QH.
1000  * This is what intel calls "bandwidth reclamation" and improves
1001  * USB performance a lot for some devices.
1002  * If we are already looping, just count it.
1003  */
1004 void
1005 uhci_add_loop(uhci_softc_t *sc) {
1006 #ifdef UHCI_DEBUG
1007 	if (uhcinoloop)
1008 		return;
1009 #endif
1010 	if (++sc->sc_loops == 1) {
1011 		DPRINTFN(5,("uhci_start_loop: add\n"));
1012 		/* Note, we don't loop back the soft pointer. */
1013 		sc->sc_last_qh->qh.qh_hlink =
1014 		    htole32(sc->sc_hctl_start->physaddr | UHCI_PTR_QH);
1015 	}
1016 }
1017 
1018 void
1019 uhci_rem_loop(uhci_softc_t *sc) {
1020 #ifdef UHCI_DEBUG
1021 	if (uhcinoloop)
1022 		return;
1023 #endif
1024 	if (--sc->sc_loops == 0) {
1025 		DPRINTFN(5,("uhci_end_loop: remove\n"));
1026 		sc->sc_last_qh->qh.qh_hlink = htole32(UHCI_PTR_T);
1027 	}
1028 }
1029 
1030 /* Add high speed control QH, called at splusb(). */
1031 void
1032 uhci_add_hs_ctrl(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
1033 {
1034 	uhci_soft_qh_t *eqh;
1035 
1036 	SPLUSBCHECK;
1037 
1038 	DPRINTFN(10, ("uhci_add_ctrl: sqh=%p\n", sqh));
1039 	eqh = sc->sc_hctl_end;
1040 	sqh->hlink       = eqh->hlink;
1041 	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
1042 	eqh->hlink       = sqh;
1043 	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
1044 	sc->sc_hctl_end = sqh;
1045 #ifdef UHCI_CTL_LOOP
1046 	uhci_add_loop(sc);
1047 #endif
1048 }
1049 
1050 /* Remove high speed control QH, called at splusb(). */
1051 void
1052 uhci_remove_hs_ctrl(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
1053 {
1054 	uhci_soft_qh_t *pqh;
1055 
1056 	SPLUSBCHECK;
1057 
1058 	DPRINTFN(10, ("uhci_remove_hs_ctrl: sqh=%p\n", sqh));
1059 #ifdef UHCI_CTL_LOOP
1060 	uhci_rem_loop(sc);
1061 #endif
1062 	/*
1063 	 * The T bit should be set in the elink of the QH so that the HC
1064 	 * doesn't follow the pointer.  This condition may fail if the
1065 	 * the transferred packet was short so that the QH still points
1066 	 * at the last used TD.
1067 	 * In this case we set the T bit and wait a little for the HC
1068 	 * to stop looking at the TD.
1069 	 */
1070 	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
1071 		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
1072 		delay(UHCI_QH_REMOVE_DELAY);
1073 	}
1074 
1075 	pqh = uhci_find_prev_qh(sc->sc_hctl_start, sqh);
1076 	pqh->hlink = sqh->hlink;
1077 	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
1078 	delay(UHCI_QH_REMOVE_DELAY);
1079 	if (sc->sc_hctl_end == sqh)
1080 		sc->sc_hctl_end = pqh;
1081 }
1082 
1083 /* Add low speed control QH, called at splusb(). */
1084 void
1085 uhci_add_ls_ctrl(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
1086 {
1087 	uhci_soft_qh_t *eqh;
1088 
1089 	SPLUSBCHECK;
1090 
1091 	DPRINTFN(10, ("uhci_add_ls_ctrl: sqh=%p\n", sqh));
1092 	eqh = sc->sc_lctl_end;
1093 	sqh->hlink = eqh->hlink;
1094 	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
1095 	eqh->hlink = sqh;
1096 	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
1097 	sc->sc_lctl_end = sqh;
1098 }
1099 
1100 /* Remove low speed control QH, called at splusb(). */
1101 void
1102 uhci_remove_ls_ctrl(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
1103 {
1104 	uhci_soft_qh_t *pqh;
1105 
1106 	SPLUSBCHECK;
1107 
1108 	DPRINTFN(10, ("uhci_remove_ls_ctrl: sqh=%p\n", sqh));
1109 	/* See comment in uhci_remove_hs_ctrl() */
1110 	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
1111 		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
1112 		delay(UHCI_QH_REMOVE_DELAY);
1113 	}
1114 	pqh = uhci_find_prev_qh(sc->sc_lctl_start, sqh);
1115 	pqh->hlink = sqh->hlink;
1116 	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
1117 	delay(UHCI_QH_REMOVE_DELAY);
1118 	if (sc->sc_lctl_end == sqh)
1119 		sc->sc_lctl_end = pqh;
1120 }
1121 
1122 /* Add bulk QH, called at splusb(). */
1123 void
1124 uhci_add_bulk(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
1125 {
1126 	uhci_soft_qh_t *eqh;
1127 
1128 	SPLUSBCHECK;
1129 
1130 	DPRINTFN(10, ("uhci_add_bulk: sqh=%p\n", sqh));
1131 	eqh = sc->sc_bulk_end;
1132 	sqh->hlink = eqh->hlink;
1133 	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
1134 	eqh->hlink = sqh;
1135 	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
1136 	sc->sc_bulk_end = sqh;
1137 	uhci_add_loop(sc);
1138 }
1139 
1140 /* Remove bulk QH, called at splusb(). */
1141 void
1142 uhci_remove_bulk(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
1143 {
1144 	uhci_soft_qh_t *pqh;
1145 
1146 	SPLUSBCHECK;
1147 
1148 	DPRINTFN(10, ("uhci_remove_bulk: sqh=%p\n", sqh));
1149 	uhci_rem_loop(sc);
1150 	/* See comment in uhci_remove_hs_ctrl() */
1151 	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
1152 		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
1153 		delay(UHCI_QH_REMOVE_DELAY);
1154 	}
1155 	pqh = uhci_find_prev_qh(sc->sc_bulk_start, sqh);
1156 	pqh->hlink       = sqh->hlink;
1157 	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
1158 	delay(UHCI_QH_REMOVE_DELAY);
1159 	if (sc->sc_bulk_end == sqh)
1160 		sc->sc_bulk_end = pqh;
1161 }
1162 
1163 Static int uhci_intr1(uhci_softc_t *);
1164 
1165 int
1166 uhci_intr(void *arg)
1167 {
1168 	uhci_softc_t *sc = arg;
1169 
1170 	if (sc->sc_dying)
1171 		return (0);
1172 
1173 	DPRINTFN(15,("uhci_intr: real interrupt\n"));
1174 	if (sc->sc_bus.use_polling) {
1175 #ifdef DIAGNOSTIC
1176 		printf("uhci_intr: ignored interrupt while polling\n");
1177 #endif
1178 		return (0);
1179 	}
1180 	return (uhci_intr1(sc));
1181 }
1182 
1183 int
1184 uhci_intr1(uhci_softc_t *sc)
1185 {
1186 	int status;
1187 	int ack;
1188 
1189 #ifdef UHCI_DEBUG
1190 	if (uhcidebug > 15) {
1191 		DPRINTF(("%s: uhci_intr1\n", USBDEVNAME(sc->sc_bus.bdev)));
1192 		uhci_dumpregs(sc);
1193 	}
1194 #endif
1195 
1196 	status = UREAD2(sc, UHCI_STS) & UHCI_STS_ALLINTRS;
1197 	if (status == 0)	/* The interrupt was not for us. */
1198 		return (0);
1199 
1200 	if (sc->sc_suspend != PWR_RESUME) {
1201 		printf("%s: interrupt while not operating ignored\n",
1202 		       USBDEVNAME(sc->sc_bus.bdev));
1203 		UWRITE2(sc, UHCI_STS, status); /* acknowledge the ints */
1204 		return (0);
1205 	}
1206 
1207 	ack = 0;
1208 	if (status & UHCI_STS_USBINT)
1209 		ack |= UHCI_STS_USBINT;
1210 	if (status & UHCI_STS_USBEI)
1211 		ack |= UHCI_STS_USBEI;
1212 	if (status & UHCI_STS_RD) {
1213 		ack |= UHCI_STS_RD;
1214 #ifdef UHCI_DEBUG
1215 		printf("%s: resume detect\n", USBDEVNAME(sc->sc_bus.bdev));
1216 #endif
1217 	}
1218 	if (status & UHCI_STS_HSE) {
1219 		ack |= UHCI_STS_HSE;
1220 		printf("%s: host system error\n", USBDEVNAME(sc->sc_bus.bdev));
1221 	}
1222 	if (status & UHCI_STS_HCPE) {
1223 		ack |= UHCI_STS_HCPE;
1224 		printf("%s: host controller process error\n",
1225 		       USBDEVNAME(sc->sc_bus.bdev));
1226 	}
1227 	if (status & UHCI_STS_HCH) {
1228 		/* no acknowledge needed */
1229 		if (!sc->sc_dying) {
1230 			printf("%s: host controller halted\n",
1231 			    USBDEVNAME(sc->sc_bus.bdev));
1232 #ifdef UHCI_DEBUG
1233 			uhci_dump_all(sc);
1234 #endif
1235 		}
1236 		sc->sc_dying = 1;
1237 	}
1238 
1239 	if (!ack)
1240 		return (0);	/* nothing to acknowledge */
1241 	UWRITE2(sc, UHCI_STS, ack); /* acknowledge the ints */
1242 
1243 	sc->sc_bus.no_intrs++;
1244 	usb_schedsoftintr(&sc->sc_bus);
1245 
1246 	DPRINTFN(10, ("%s: uhci_intr: exit\n", USBDEVNAME(sc->sc_bus.bdev)));
1247 
1248 	return (1);
1249 }
1250 
1251 void
1252 uhci_softintr(void *v)
1253 {
1254 	uhci_softc_t *sc = v;
1255 	uhci_intr_info_t *ii;
1256 
1257 	DPRINTFN(10,("%s: uhci_softintr (%d)\n", USBDEVNAME(sc->sc_bus.bdev),
1258 		     sc->sc_bus.intr_context));
1259 
1260 	sc->sc_bus.intr_context++;
1261 
1262 	/*
1263 	 * Interrupts on UHCI really suck.  When the host controller
1264 	 * interrupts because a transfer is completed there is no
1265 	 * way of knowing which transfer it was.  You can scan down
1266 	 * the TDs and QHs of the previous frame to limit the search,
1267 	 * but that assumes that the interrupt was not delayed by more
1268 	 * than 1 ms, which may not always be true (e.g. after debug
1269 	 * output on a slow console).
1270 	 * We scan all interrupt descriptors to see if any have
1271 	 * completed.
1272 	 */
1273 	for (ii = LIST_FIRST(&sc->sc_intrhead); ii; ii = LIST_NEXT(ii, list))
1274 		uhci_check_intr(sc, ii);
1275 
1276 	if (sc->sc_softwake) {
1277 		sc->sc_softwake = 0;
1278 		wakeup(&sc->sc_softwake);
1279 	}
1280 
1281 	sc->sc_bus.intr_context--;
1282 }
1283 
1284 /* Check for an interrupt. */
1285 void
1286 uhci_check_intr(uhci_softc_t *sc, uhci_intr_info_t *ii)
1287 {
1288 	uhci_soft_td_t *std, *lstd;
1289 	u_int32_t status;
1290 
1291 	DPRINTFN(15, ("uhci_check_intr: ii=%p\n", ii));
1292 #ifdef DIAGNOSTIC
1293 	if (ii == NULL) {
1294 		printf("uhci_check_intr: no ii? %p\n", ii);
1295 		return;
1296 	}
1297 #endif
1298 	if (ii->xfer->status == USBD_CANCELLED ||
1299 	    ii->xfer->status == USBD_TIMEOUT) {
1300 		DPRINTF(("uhci_check_intr: aborted xfer=%p\n", ii->xfer));
1301 		return;
1302 	}
1303 
1304 	if (ii->stdstart == NULL)
1305 		return;
1306 	lstd = ii->stdend;
1307 #ifdef DIAGNOSTIC
1308 	if (lstd == NULL) {
1309 		printf("uhci_check_intr: std==0\n");
1310 		return;
1311 	}
1312 #endif
1313 	/*
1314 	 * If the last TD is still active we need to check whether there
1315 	 * is a an error somewhere in the middle, or whether there was a
1316 	 * short packet (SPD and not ACTIVE).
1317 	 */
1318 	if (le32toh(lstd->td.td_status) & UHCI_TD_ACTIVE) {
1319 		DPRINTFN(12, ("uhci_check_intr: active ii=%p\n", ii));
1320 		for (std = ii->stdstart; std != lstd; std = std->link.std) {
1321 			status = le32toh(std->td.td_status);
1322 			/* If there's an active TD the xfer isn't done. */
1323 			if (status & UHCI_TD_ACTIVE)
1324 				break;
1325 			/* Any kind of error makes the xfer done. */
1326 			if (status & UHCI_TD_STALLED)
1327 				goto done;
1328 			/* We want short packets, and it is short: it's done */
1329 			if ((status & UHCI_TD_SPD) &&
1330 			      UHCI_TD_GET_ACTLEN(status) <
1331 			      UHCI_TD_GET_MAXLEN(le32toh(std->td.td_token)))
1332 				goto done;
1333 		}
1334 		DPRINTFN(12, ("uhci_check_intr: ii=%p std=%p still active\n",
1335 			      ii, ii->stdstart));
1336 		return;
1337 	}
1338  done:
1339 	DPRINTFN(12, ("uhci_check_intr: ii=%p done\n", ii));
1340 	usb_uncallout(ii->xfer->timeout_handle, uhci_timeout, ii);
1341 	uhci_idone(ii);
1342 }
1343 
1344 /* Called at splusb() */
1345 void
1346 uhci_idone(uhci_intr_info_t *ii)
1347 {
1348 	usbd_xfer_handle xfer = ii->xfer;
1349 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
1350 	uhci_soft_td_t *std;
1351 	u_int32_t status = 0, nstatus;
1352 	int actlen;
1353 
1354 	DPRINTFN(12, ("uhci_idone: ii=%p\n", ii));
1355 #ifdef DIAGNOSTIC
1356 	{
1357 		int s = splhigh();
1358 		if (ii->isdone) {
1359 			splx(s);
1360 #ifdef UHCI_DEBUG
1361 			printf("uhci_idone: ii is done!\n   ");
1362 			uhci_dump_ii(ii);
1363 #else
1364 			printf("uhci_idone: ii=%p is done!\n", ii);
1365 #endif
1366 			return;
1367 		}
1368 		ii->isdone = 1;
1369 		splx(s);
1370 	}
1371 #endif
1372 
1373 	if (xfer->nframes != 0) {
1374 		/* Isoc transfer, do things differently. */
1375 		uhci_soft_td_t **stds = upipe->u.iso.stds;
1376 		int i, n, nframes, len;
1377 
1378 		DPRINTFN(5,("uhci_idone: ii=%p isoc ready\n", ii));
1379 
1380 		nframes = xfer->nframes;
1381 		actlen = 0;
1382 		n = UXFER(xfer)->curframe;
1383 		for (i = 0; i < nframes; i++) {
1384 			std = stds[n];
1385 #ifdef UHCI_DEBUG
1386 			if (uhcidebug > 5) {
1387 				DPRINTFN(-1,("uhci_idone: isoc TD %d\n", i));
1388 				uhci_dump_td(std);
1389 			}
1390 #endif
1391 			if (++n >= UHCI_VFRAMELIST_COUNT)
1392 				n = 0;
1393 			status = le32toh(std->td.td_status);
1394 			len = UHCI_TD_GET_ACTLEN(status);
1395 			xfer->frlengths[i] = len;
1396 			actlen += len;
1397 		}
1398 		upipe->u.iso.inuse -= nframes;
1399 		xfer->actlen = actlen;
1400 		xfer->status = USBD_NORMAL_COMPLETION;
1401 		goto end;
1402 	}
1403 
1404 #ifdef UHCI_DEBUG
1405 	DPRINTFN(10, ("uhci_idone: ii=%p, xfer=%p, pipe=%p ready\n",
1406 		      ii, xfer, upipe));
1407 	if (uhcidebug > 10)
1408 		uhci_dump_tds(ii->stdstart);
1409 #endif
1410 
1411 	/* The transfer is done, compute actual length and status. */
1412 	actlen = 0;
1413 	for (std = ii->stdstart; std != NULL; std = std->link.std) {
1414 		nstatus = le32toh(std->td.td_status);
1415 		if (nstatus & UHCI_TD_ACTIVE)
1416 			break;
1417 
1418 		status = nstatus;
1419 		if (UHCI_TD_GET_PID(le32toh(std->td.td_token)) !=
1420 			UHCI_TD_PID_SETUP)
1421 			actlen += UHCI_TD_GET_ACTLEN(status);
1422 	}
1423 	/* If there are left over TDs we need to update the toggle. */
1424 	if (std != NULL)
1425 		upipe->nexttoggle = UHCI_TD_GET_DT(le32toh(std->td.td_token));
1426 
1427 	status &= UHCI_TD_ERROR;
1428 	DPRINTFN(10, ("uhci_idone: actlen=%d, status=0x%x\n",
1429 		      actlen, status));
1430 	xfer->actlen = actlen;
1431 	if (status != 0) {
1432 #ifdef UHCI_DEBUG
1433 		char sbuf[128];
1434 
1435 		bitmask_snprintf((u_int32_t)status,
1436 				 "\20\22BITSTUFF\23CRCTO\24NAK\25"
1437 				 "BABBLE\26DBUFFER\27STALLED\30ACTIVE",
1438 				 sbuf, sizeof(sbuf));
1439 
1440 		DPRINTFN((status == UHCI_TD_STALLED)*10,
1441 			 ("uhci_idone: error, addr=%d, endpt=0x%02x, "
1442 			  "status 0x%s\n",
1443 			  xfer->pipe->device->address,
1444 			  xfer->pipe->endpoint->edesc->bEndpointAddress,
1445 			  sbuf));
1446 #endif
1447 
1448 		if (status == UHCI_TD_STALLED)
1449 			xfer->status = USBD_STALLED;
1450 		else
1451 			xfer->status = USBD_IOERROR; /* more info XXX */
1452 	} else {
1453 		xfer->status = USBD_NORMAL_COMPLETION;
1454 	}
1455 
1456  end:
1457 	usb_transfer_complete(xfer);
1458 	DPRINTFN(12, ("uhci_idone: ii=%p done\n", ii));
1459 }
1460 
1461 /*
1462  * Called when a request does not complete.
1463  */
1464 void
1465 uhci_timeout(void *addr)
1466 {
1467 	uhci_intr_info_t *ii = addr;
1468 	struct uhci_xfer *uxfer = UXFER(ii->xfer);
1469 	struct uhci_pipe *upipe = (struct uhci_pipe *)uxfer->xfer.pipe;
1470 	uhci_softc_t *sc = (uhci_softc_t *)upipe->pipe.device->bus;
1471 
1472 	DPRINTF(("uhci_timeout: uxfer=%p\n", uxfer));
1473 
1474 	if (sc->sc_dying) {
1475 		uhci_abort_xfer(&uxfer->xfer, USBD_TIMEOUT);
1476 		return;
1477 	}
1478 
1479 	/* Execute the abort in a process context. */
1480 	usb_init_task(&uxfer->abort_task, uhci_timeout_task, ii->xfer);
1481 	usb_add_task(uxfer->xfer.pipe->device, &uxfer->abort_task);
1482 }
1483 
1484 void
1485 uhci_timeout_task(void *addr)
1486 {
1487 	usbd_xfer_handle xfer = addr;
1488 	int s;
1489 
1490 	DPRINTF(("uhci_timeout_task: xfer=%p\n", xfer));
1491 
1492 	s = splusb();
1493 	uhci_abort_xfer(xfer, USBD_TIMEOUT);
1494 	splx(s);
1495 }
1496 
1497 /*
1498  * Wait here until controller claims to have an interrupt.
1499  * Then call uhci_intr and return.  Use timeout to avoid waiting
1500  * too long.
1501  * Only used during boot when interrupts are not enabled yet.
1502  */
1503 void
1504 uhci_waitintr(uhci_softc_t *sc, usbd_xfer_handle xfer)
1505 {
1506 	int timo = xfer->timeout;
1507 	uhci_intr_info_t *ii;
1508 
1509 	DPRINTFN(10,("uhci_waitintr: timeout = %dms\n", timo));
1510 
1511 	xfer->status = USBD_IN_PROGRESS;
1512 	for (; timo >= 0; timo--) {
1513 		usb_delay_ms(&sc->sc_bus, 1);
1514 		DPRINTFN(20,("uhci_waitintr: 0x%04x\n", UREAD2(sc, UHCI_STS)));
1515 		if (UREAD2(sc, UHCI_STS) & UHCI_STS_USBINT) {
1516 			uhci_intr1(sc);
1517 			if (xfer->status != USBD_IN_PROGRESS)
1518 				return;
1519 		}
1520 	}
1521 
1522 	/* Timeout */
1523 	DPRINTF(("uhci_waitintr: timeout\n"));
1524 	for (ii = LIST_FIRST(&sc->sc_intrhead);
1525 	     ii != NULL && ii->xfer != xfer;
1526 	     ii = LIST_NEXT(ii, list))
1527 		;
1528 #ifdef DIAGNOSTIC
1529 	if (ii == NULL)
1530 		panic("uhci_waitintr: lost intr_info\n");
1531 #endif
1532 	uhci_idone(ii);
1533 }
1534 
1535 void
1536 uhci_poll(struct usbd_bus *bus)
1537 {
1538 	uhci_softc_t *sc = (uhci_softc_t *)bus;
1539 
1540 	if (UREAD2(sc, UHCI_STS) & UHCI_STS_USBINT)
1541 		uhci_intr1(sc);
1542 }
1543 
1544 void
1545 uhci_reset(uhci_softc_t *sc)
1546 {
1547 	int n;
1548 
1549 	UHCICMD(sc, UHCI_CMD_HCRESET);
1550 	/* The reset bit goes low when the controller is done. */
1551 	for (n = 0; n < UHCI_RESET_TIMEOUT &&
1552 		    (UREAD2(sc, UHCI_CMD) & UHCI_CMD_HCRESET); n++)
1553 		usb_delay_ms(&sc->sc_bus, 1);
1554 	if (n >= UHCI_RESET_TIMEOUT)
1555 		printf("%s: controller did not reset\n",
1556 		       USBDEVNAME(sc->sc_bus.bdev));
1557 }
1558 
1559 usbd_status
1560 uhci_run(uhci_softc_t *sc, int run)
1561 {
1562 	int s, n, running;
1563 	u_int16_t cmd;
1564 
1565 	run = run != 0;
1566 	s = splhardusb();
1567 	DPRINTF(("uhci_run: setting run=%d\n", run));
1568 	cmd = UREAD2(sc, UHCI_CMD);
1569 	if (run)
1570 		cmd |= UHCI_CMD_RS;
1571 	else
1572 		cmd &= ~UHCI_CMD_RS;
1573 	UHCICMD(sc, cmd);
1574 	for(n = 0; n < 10; n++) {
1575 		running = !(UREAD2(sc, UHCI_STS) & UHCI_STS_HCH);
1576 		/* return when we've entered the state we want */
1577 		if (run == running) {
1578 			splx(s);
1579 			DPRINTF(("uhci_run: done cmd=0x%x sts=0x%x\n",
1580 				 UREAD2(sc, UHCI_CMD), UREAD2(sc, UHCI_STS)));
1581 			return (USBD_NORMAL_COMPLETION);
1582 		}
1583 		usb_delay_ms(&sc->sc_bus, 1);
1584 	}
1585 	splx(s);
1586 	printf("%s: cannot %s\n", USBDEVNAME(sc->sc_bus.bdev),
1587 	       run ? "start" : "stop");
1588 	return (USBD_IOERROR);
1589 }
1590 
1591 /*
1592  * Memory management routines.
1593  *  uhci_alloc_std allocates TDs
1594  *  uhci_alloc_sqh allocates QHs
1595  * These two routines do their own free list management,
1596  * partly for speed, partly because allocating DMAable memory
1597  * has page size granularaity so much memory would be wasted if
1598  * only one TD/QH (32 bytes) was placed in each allocated chunk.
1599  */
1600 
1601 uhci_soft_td_t *
1602 uhci_alloc_std(uhci_softc_t *sc)
1603 {
1604 	uhci_soft_td_t *std;
1605 	usbd_status err;
1606 	int i, offs;
1607 	usb_dma_t dma;
1608 
1609 	if (sc->sc_freetds == NULL) {
1610 		DPRINTFN(2,("uhci_alloc_std: allocating chunk\n"));
1611 		err = usb_allocmem(&sc->sc_bus, UHCI_STD_SIZE * UHCI_STD_CHUNK,
1612 			  UHCI_TD_ALIGN, &dma);
1613 		if (err)
1614 			return (0);
1615 		for(i = 0; i < UHCI_STD_CHUNK; i++) {
1616 			offs = i * UHCI_STD_SIZE;
1617 			std = KERNADDR(&dma, offs);
1618 			std->physaddr = DMAADDR(&dma, offs);
1619 			std->link.std = sc->sc_freetds;
1620 			sc->sc_freetds = std;
1621 		}
1622 	}
1623 	std = sc->sc_freetds;
1624 	sc->sc_freetds = std->link.std;
1625 	memset(&std->td, 0, sizeof(uhci_td_t));
1626 	return std;
1627 }
1628 
1629 void
1630 uhci_free_std(uhci_softc_t *sc, uhci_soft_td_t *std)
1631 {
1632 #ifdef DIAGNOSTIC
1633 #define TD_IS_FREE 0x12345678
1634 	if (le32toh(std->td.td_token) == TD_IS_FREE) {
1635 		printf("uhci_free_std: freeing free TD %p\n", std);
1636 		return;
1637 	}
1638 	std->td.td_token = htole32(TD_IS_FREE);
1639 #endif
1640 	std->link.std = sc->sc_freetds;
1641 	sc->sc_freetds = std;
1642 }
1643 
1644 uhci_soft_qh_t *
1645 uhci_alloc_sqh(uhci_softc_t *sc)
1646 {
1647 	uhci_soft_qh_t *sqh;
1648 	usbd_status err;
1649 	int i, offs;
1650 	usb_dma_t dma;
1651 
1652 	if (sc->sc_freeqhs == NULL) {
1653 		DPRINTFN(2, ("uhci_alloc_sqh: allocating chunk\n"));
1654 		err = usb_allocmem(&sc->sc_bus, UHCI_SQH_SIZE * UHCI_SQH_CHUNK,
1655 			  UHCI_QH_ALIGN, &dma);
1656 		if (err)
1657 			return (0);
1658 		for(i = 0; i < UHCI_SQH_CHUNK; i++) {
1659 			offs = i * UHCI_SQH_SIZE;
1660 			sqh = KERNADDR(&dma, offs);
1661 			sqh->physaddr = DMAADDR(&dma, offs);
1662 			sqh->hlink = sc->sc_freeqhs;
1663 			sc->sc_freeqhs = sqh;
1664 		}
1665 	}
1666 	sqh = sc->sc_freeqhs;
1667 	sc->sc_freeqhs = sqh->hlink;
1668 	memset(&sqh->qh, 0, sizeof(uhci_qh_t));
1669 	return (sqh);
1670 }
1671 
1672 void
1673 uhci_free_sqh(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
1674 {
1675 	sqh->hlink = sc->sc_freeqhs;
1676 	sc->sc_freeqhs = sqh;
1677 }
1678 
1679 void
1680 uhci_free_std_chain(uhci_softc_t *sc, uhci_soft_td_t *std,
1681 		    uhci_soft_td_t *stdend)
1682 {
1683 	uhci_soft_td_t *p;
1684 
1685 	for (; std != stdend; std = p) {
1686 		p = std->link.std;
1687 		uhci_free_std(sc, std);
1688 	}
1689 }
1690 
1691 usbd_status
1692 uhci_alloc_std_chain(struct uhci_pipe *upipe, uhci_softc_t *sc, int len,
1693 		     int rd, u_int16_t flags, usb_dma_t *dma,
1694 		     uhci_soft_td_t **sp, uhci_soft_td_t **ep)
1695 {
1696 	uhci_soft_td_t *p, *lastp;
1697 	uhci_physaddr_t lastlink;
1698 	int i, ntd, l, tog, maxp;
1699 	u_int32_t status;
1700 	int addr = upipe->pipe.device->address;
1701 	int endpt = upipe->pipe.endpoint->edesc->bEndpointAddress;
1702 
1703 	DPRINTFN(8, ("uhci_alloc_std_chain: addr=%d endpt=%d len=%d speed=%d "
1704 		      "flags=0x%x\n", addr, UE_GET_ADDR(endpt), len,
1705 		      upipe->pipe.device->speed, flags));
1706 	maxp = UGETW(upipe->pipe.endpoint->edesc->wMaxPacketSize);
1707 	if (maxp == 0) {
1708 		printf("uhci_alloc_std_chain: maxp=0\n");
1709 		return (USBD_INVAL);
1710 	}
1711 	ntd = (len + maxp - 1) / maxp;
1712 	if ((flags & USBD_FORCE_SHORT_XFER) && len % maxp == 0)
1713 		ntd++;
1714 	DPRINTFN(10, ("uhci_alloc_std_chain: maxp=%d ntd=%d\n", maxp, ntd));
1715 	if (ntd == 0) {
1716 		*sp = *ep = 0;
1717 		DPRINTFN(-1,("uhci_alloc_std_chain: ntd=0\n"));
1718 		return (USBD_NORMAL_COMPLETION);
1719 	}
1720 	tog = upipe->nexttoggle;
1721 	if (ntd % 2 == 0)
1722 		tog ^= 1;
1723 	upipe->nexttoggle = tog ^ 1;
1724 	lastp = NULL;
1725 	lastlink = UHCI_PTR_T;
1726 	ntd--;
1727 	status = UHCI_TD_ZERO_ACTLEN(UHCI_TD_SET_ERRCNT(3) | UHCI_TD_ACTIVE);
1728 	if (upipe->pipe.device->speed == USB_SPEED_LOW)
1729 		status |= UHCI_TD_LS;
1730 	if (flags & USBD_SHORT_XFER_OK)
1731 		status |= UHCI_TD_SPD;
1732 	for (i = ntd; i >= 0; i--) {
1733 		p = uhci_alloc_std(sc);
1734 		if (p == NULL) {
1735 			uhci_free_std_chain(sc, lastp, NULL);
1736 			return (USBD_NOMEM);
1737 		}
1738 		p->link.std = lastp;
1739 		p->td.td_link = htole32(lastlink | UHCI_PTR_VF | UHCI_PTR_TD);
1740 		lastp = p;
1741 		lastlink = p->physaddr;
1742 		p->td.td_status = htole32(status);
1743 		if (i == ntd) {
1744 			/* last TD */
1745 			l = len % maxp;
1746 			if (l == 0 && !(flags & USBD_FORCE_SHORT_XFER))
1747 				l = maxp;
1748 			*ep = p;
1749 		} else
1750 			l = maxp;
1751 		p->td.td_token =
1752 		    htole32(rd ? UHCI_TD_IN (l, endpt, addr, tog) :
1753 				 UHCI_TD_OUT(l, endpt, addr, tog));
1754 		p->td.td_buffer = htole32(DMAADDR(dma, i * maxp));
1755 		tog ^= 1;
1756 	}
1757 	*sp = lastp;
1758 	DPRINTFN(10, ("uhci_alloc_std_chain: nexttog=%d\n",
1759 		      upipe->nexttoggle));
1760 	return (USBD_NORMAL_COMPLETION);
1761 }
1762 
1763 void
1764 uhci_device_clear_toggle(usbd_pipe_handle pipe)
1765 {
1766 	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
1767 	upipe->nexttoggle = 0;
1768 }
1769 
1770 void
1771 uhci_noop(usbd_pipe_handle pipe)
1772 {
1773 }
1774 
1775 usbd_status
1776 uhci_device_bulk_transfer(usbd_xfer_handle xfer)
1777 {
1778 	usbd_status err;
1779 
1780 	/* Insert last in queue. */
1781 	err = usb_insert_transfer(xfer);
1782 	if (err)
1783 		return (err);
1784 
1785 	/*
1786 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
1787 	 * so start it first.
1788 	 */
1789 	return (uhci_device_bulk_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
1790 }
1791 
1792 usbd_status
1793 uhci_device_bulk_start(usbd_xfer_handle xfer)
1794 {
1795 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
1796 	usbd_device_handle dev = upipe->pipe.device;
1797 	uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
1798 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
1799 	uhci_soft_td_t *data, *dataend;
1800 	uhci_soft_qh_t *sqh;
1801 	usbd_status err;
1802 	int len, isread, endpt;
1803 	int s;
1804 
1805 	DPRINTFN(3, ("uhci_device_bulk_transfer: xfer=%p len=%d flags=%d\n",
1806 		     xfer, xfer->length, xfer->flags));
1807 
1808 	if (sc->sc_dying)
1809 		return (USBD_IOERROR);
1810 
1811 #ifdef DIAGNOSTIC
1812 	if (xfer->rqflags & URQ_REQUEST)
1813 		panic("uhci_device_bulk_transfer: a request\n");
1814 #endif
1815 
1816 	len = xfer->length;
1817 	endpt = upipe->pipe.endpoint->edesc->bEndpointAddress;
1818 	isread = UE_GET_DIR(endpt) == UE_DIR_IN;
1819 	sqh = upipe->u.bulk.sqh;
1820 
1821 	upipe->u.bulk.isread = isread;
1822 	upipe->u.bulk.length = len;
1823 
1824 	err = uhci_alloc_std_chain(upipe, sc, len, isread, xfer->flags,
1825 				   &xfer->dmabuf, &data, &dataend);
1826 	if (err)
1827 		return (err);
1828 	dataend->td.td_status |= htole32(UHCI_TD_IOC);
1829 
1830 #ifdef UHCI_DEBUG
1831 	if (uhcidebug > 8) {
1832 		DPRINTF(("uhci_device_bulk_transfer: data(1)\n"));
1833 		uhci_dump_tds(data);
1834 	}
1835 #endif
1836 
1837 	/* Set up interrupt info. */
1838 	ii->xfer = xfer;
1839 	ii->stdstart = data;
1840 	ii->stdend = dataend;
1841 #ifdef DIAGNOSTIC
1842 	if (!ii->isdone) {
1843 		printf("uhci_device_bulk_transfer: not done, ii=%p\n", ii);
1844 	}
1845 	ii->isdone = 0;
1846 #endif
1847 
1848 	sqh->elink = data;
1849 	sqh->qh.qh_elink = htole32(data->physaddr | UHCI_PTR_TD);
1850 
1851 	s = splusb();
1852 	uhci_add_bulk(sc, sqh);
1853 	uhci_add_intr_info(sc, ii);
1854 
1855 	if (xfer->timeout && !sc->sc_bus.use_polling) {
1856 		usb_callout(xfer->timeout_handle, MS_TO_TICKS(xfer->timeout),
1857 			    uhci_timeout, ii);
1858 	}
1859 	xfer->status = USBD_IN_PROGRESS;
1860 	splx(s);
1861 
1862 #ifdef UHCI_DEBUG
1863 	if (uhcidebug > 10) {
1864 		DPRINTF(("uhci_device_bulk_transfer: data(2)\n"));
1865 		uhci_dump_tds(data);
1866 	}
1867 #endif
1868 
1869 	if (sc->sc_bus.use_polling)
1870 		uhci_waitintr(sc, xfer);
1871 
1872 	return (USBD_IN_PROGRESS);
1873 }
1874 
1875 /* Abort a device bulk request. */
1876 void
1877 uhci_device_bulk_abort(usbd_xfer_handle xfer)
1878 {
1879 	DPRINTF(("uhci_device_bulk_abort:\n"));
1880 	uhci_abort_xfer(xfer, USBD_CANCELLED);
1881 }
1882 
1883 /*
1884  * Abort a device request.
1885  * If this routine is called at splusb() it guarantees that the request
1886  * will be removed from the hardware scheduling and that the callback
1887  * for it will be called with USBD_CANCELLED status.
1888  * It's impossible to guarantee that the requested transfer will not
1889  * have happened since the hardware runs concurrently.
1890  * If the transaction has already happened we rely on the ordinary
1891  * interrupt processing to process it.
1892  */
1893 void
1894 uhci_abort_xfer(usbd_xfer_handle xfer, usbd_status status)
1895 {
1896 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
1897 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
1898 	uhci_softc_t *sc = (uhci_softc_t *)upipe->pipe.device->bus;
1899 	uhci_soft_td_t *std;
1900 	int s;
1901 
1902 	DPRINTFN(1,("uhci_abort_xfer: xfer=%p, status=%d\n", xfer, status));
1903 
1904 	if (sc->sc_dying) {
1905 		/* If we're dying, just do the software part. */
1906 		s = splusb();
1907 		xfer->status = status;	/* make software ignore it */
1908 		usb_uncallout(xfer->timeout_handle, uhci_timeout, xfer);
1909 		usb_transfer_complete(xfer);
1910 		splx(s);
1911 	}
1912 
1913 	if (xfer->device->bus->intr_context || !curproc)
1914 		panic("uhci_abort_xfer: not in process context\n");
1915 
1916 	/*
1917 	 * Step 1: Make interrupt routine and hardware ignore xfer.
1918 	 */
1919 	s = splusb();
1920 	xfer->status = status;	/* make software ignore it */
1921 	usb_uncallout(xfer->timeout_handle, uhci_timeout, ii);
1922 	DPRINTFN(1,("uhci_abort_xfer: stop ii=%p\n", ii));
1923 	for (std = ii->stdstart; std != NULL; std = std->link.std)
1924 		std->td.td_status &= htole32(~(UHCI_TD_ACTIVE | UHCI_TD_IOC));
1925 	splx(s);
1926 
1927 	/*
1928 	 * Step 2: Wait until we know hardware has finished any possible
1929 	 * use of the xfer.  Also make sure the soft interrupt routine
1930 	 * has run.
1931 	 */
1932 	usb_delay_ms(upipe->pipe.device->bus, 2); /* Hardware finishes in 1ms */
1933 	s = splusb();
1934 	sc->sc_softwake = 1;
1935 	usb_schedsoftintr(&sc->sc_bus);
1936 	DPRINTFN(1,("uhci_abort_xfer: tsleep\n"));
1937 	tsleep(&sc->sc_softwake, PZERO, "uhciab", 0);
1938 	splx(s);
1939 
1940 	/*
1941 	 * Step 3: Execute callback.
1942 	 */
1943 	xfer->hcpriv = ii;
1944 
1945 	DPRINTFN(1,("uhci_abort_xfer: callback\n"));
1946 	s = splusb();
1947 #ifdef DIAGNOSTIC
1948 	ii->isdone = 1;
1949 #endif
1950 	usb_transfer_complete(xfer);
1951 	splx(s);
1952 }
1953 
1954 /* Close a device bulk pipe. */
1955 void
1956 uhci_device_bulk_close(usbd_pipe_handle pipe)
1957 {
1958 	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
1959 	usbd_device_handle dev = upipe->pipe.device;
1960 	uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
1961 
1962 	uhci_free_sqh(sc, upipe->u.bulk.sqh);
1963 }
1964 
1965 usbd_status
1966 uhci_device_ctrl_transfer(usbd_xfer_handle xfer)
1967 {
1968 	usbd_status err;
1969 
1970 	/* Insert last in queue. */
1971 	err = usb_insert_transfer(xfer);
1972 	if (err)
1973 		return (err);
1974 
1975 	/*
1976 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
1977 	 * so start it first.
1978 	 */
1979 	return (uhci_device_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
1980 }
1981 
1982 usbd_status
1983 uhci_device_ctrl_start(usbd_xfer_handle xfer)
1984 {
1985 	uhci_softc_t *sc = (uhci_softc_t *)xfer->pipe->device->bus;
1986 	usbd_status err;
1987 
1988 	if (sc->sc_dying)
1989 		return (USBD_IOERROR);
1990 
1991 #ifdef DIAGNOSTIC
1992 	if (!(xfer->rqflags & URQ_REQUEST))
1993 		panic("uhci_device_ctrl_transfer: not a request\n");
1994 #endif
1995 
1996 	err = uhci_device_request(xfer);
1997 	if (err)
1998 		return (err);
1999 
2000 	if (sc->sc_bus.use_polling)
2001 		uhci_waitintr(sc, xfer);
2002 	return (USBD_IN_PROGRESS);
2003 }
2004 
2005 usbd_status
2006 uhci_device_intr_transfer(usbd_xfer_handle xfer)
2007 {
2008 	usbd_status err;
2009 
2010 	/* Insert last in queue. */
2011 	err = usb_insert_transfer(xfer);
2012 	if (err)
2013 		return (err);
2014 
2015 	/*
2016 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
2017 	 * so start it first.
2018 	 */
2019 	return (uhci_device_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2020 }
2021 
2022 usbd_status
2023 uhci_device_intr_start(usbd_xfer_handle xfer)
2024 {
2025 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2026 	usbd_device_handle dev = upipe->pipe.device;
2027 	uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
2028 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
2029 	uhci_soft_td_t *data, *dataend;
2030 	uhci_soft_qh_t *sqh;
2031 	usbd_status err;
2032 	int i, s;
2033 
2034 	if (sc->sc_dying)
2035 		return (USBD_IOERROR);
2036 
2037 	DPRINTFN(3,("uhci_device_intr_transfer: xfer=%p len=%d flags=%d\n",
2038 		    xfer, xfer->length, xfer->flags));
2039 
2040 #ifdef DIAGNOSTIC
2041 	if (xfer->rqflags & URQ_REQUEST)
2042 		panic("uhci_device_intr_transfer: a request\n");
2043 #endif
2044 
2045 	err = uhci_alloc_std_chain(upipe, sc, xfer->length, 1, xfer->flags,
2046 				   &xfer->dmabuf, &data, &dataend);
2047 	if (err)
2048 		return (err);
2049 	dataend->td.td_status |= htole32(UHCI_TD_IOC);
2050 
2051 #ifdef UHCI_DEBUG
2052 	if (uhcidebug > 10) {
2053 		DPRINTF(("uhci_device_intr_transfer: data(1)\n"));
2054 		uhci_dump_tds(data);
2055 		uhci_dump_qh(upipe->u.intr.qhs[0]);
2056 	}
2057 #endif
2058 
2059 	s = splusb();
2060 	/* Set up interrupt info. */
2061 	ii->xfer = xfer;
2062 	ii->stdstart = data;
2063 	ii->stdend = dataend;
2064 #ifdef DIAGNOSTIC
2065 	if (!ii->isdone) {
2066 		printf("uhci_device_intr_transfer: not done, ii=%p\n", ii);
2067 	}
2068 	ii->isdone = 0;
2069 #endif
2070 
2071 	DPRINTFN(10,("uhci_device_intr_transfer: qhs[0]=%p\n",
2072 		     upipe->u.intr.qhs[0]));
2073 	for (i = 0; i < upipe->u.intr.npoll; i++) {
2074 		sqh = upipe->u.intr.qhs[i];
2075 		sqh->elink = data;
2076 		sqh->qh.qh_elink = htole32(data->physaddr | UHCI_PTR_TD);
2077 	}
2078 	uhci_add_intr_info(sc, ii);
2079 	xfer->status = USBD_IN_PROGRESS;
2080 	splx(s);
2081 
2082 #ifdef UHCI_DEBUG
2083 	if (uhcidebug > 10) {
2084 		DPRINTF(("uhci_device_intr_transfer: data(2)\n"));
2085 		uhci_dump_tds(data);
2086 		uhci_dump_qh(upipe->u.intr.qhs[0]);
2087 	}
2088 #endif
2089 
2090 	return (USBD_IN_PROGRESS);
2091 }
2092 
2093 /* Abort a device control request. */
2094 void
2095 uhci_device_ctrl_abort(usbd_xfer_handle xfer)
2096 {
2097 	DPRINTF(("uhci_device_ctrl_abort:\n"));
2098 	uhci_abort_xfer(xfer, USBD_CANCELLED);
2099 }
2100 
2101 /* Close a device control pipe. */
2102 void
2103 uhci_device_ctrl_close(usbd_pipe_handle pipe)
2104 {
2105 }
2106 
2107 /* Abort a device interrupt request. */
2108 void
2109 uhci_device_intr_abort(usbd_xfer_handle xfer)
2110 {
2111 	DPRINTFN(1,("uhci_device_intr_abort: xfer=%p\n", xfer));
2112 	if (xfer->pipe->intrxfer == xfer) {
2113 		DPRINTFN(1,("uhci_device_intr_abort: remove\n"));
2114 		xfer->pipe->intrxfer = NULL;
2115 	}
2116 	uhci_abort_xfer(xfer, USBD_CANCELLED);
2117 }
2118 
2119 /* Close a device interrupt pipe. */
2120 void
2121 uhci_device_intr_close(usbd_pipe_handle pipe)
2122 {
2123 	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
2124 	uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
2125 	int i, npoll;
2126 	int s;
2127 
2128 	/* Unlink descriptors from controller data structures. */
2129 	npoll = upipe->u.intr.npoll;
2130 	s = splusb();
2131 	for (i = 0; i < npoll; i++)
2132 		uhci_remove_intr(sc, upipe->u.intr.qhs[i]);
2133 	splx(s);
2134 
2135 	/*
2136 	 * We now have to wait for any activity on the physical
2137 	 * descriptors to stop.
2138 	 */
2139 	usb_delay_ms(&sc->sc_bus, 2);
2140 
2141 	for(i = 0; i < npoll; i++)
2142 		uhci_free_sqh(sc, upipe->u.intr.qhs[i]);
2143 	free(upipe->u.intr.qhs, M_USBHC);
2144 
2145 	/* XXX free other resources */
2146 }
2147 
2148 usbd_status
2149 uhci_device_request(usbd_xfer_handle xfer)
2150 {
2151 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2152 	usb_device_request_t *req = &xfer->request;
2153 	usbd_device_handle dev = upipe->pipe.device;
2154 	uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
2155 	int addr = dev->address;
2156 	int endpt = upipe->pipe.endpoint->edesc->bEndpointAddress;
2157 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
2158 	uhci_soft_td_t *setup, *data, *stat, *next, *dataend;
2159 	uhci_soft_qh_t *sqh;
2160 	int len;
2161 	u_int32_t ls;
2162 	usbd_status err;
2163 	int isread;
2164 	int s;
2165 
2166 	DPRINTFN(3,("uhci_device_control type=0x%02x, request=0x%02x, "
2167 		    "wValue=0x%04x, wIndex=0x%04x len=%d, addr=%d, endpt=%d\n",
2168 		    req->bmRequestType, req->bRequest, UGETW(req->wValue),
2169 		    UGETW(req->wIndex), UGETW(req->wLength),
2170 		    addr, endpt));
2171 
2172 	ls = dev->speed == USB_SPEED_LOW ? UHCI_TD_LS : 0;
2173 	isread = req->bmRequestType & UT_READ;
2174 	len = UGETW(req->wLength);
2175 
2176 	setup = upipe->u.ctl.setup;
2177 	stat = upipe->u.ctl.stat;
2178 	sqh = upipe->u.ctl.sqh;
2179 
2180 	/* Set up data transaction */
2181 	if (len != 0) {
2182 		upipe->nexttoggle = 1;
2183 		err = uhci_alloc_std_chain(upipe, sc, len, isread, xfer->flags,
2184 					   &xfer->dmabuf, &data, &dataend);
2185 		if (err)
2186 			return (err);
2187 		next = data;
2188 		dataend->link.std = stat;
2189 		dataend->td.td_link = htole32(stat->physaddr | UHCI_PTR_VF | UHCI_PTR_TD);
2190 	} else {
2191 		next = stat;
2192 	}
2193 	upipe->u.ctl.length = len;
2194 
2195 	memcpy(KERNADDR(&upipe->u.ctl.reqdma, 0), req, sizeof *req);
2196 
2197 	setup->link.std = next;
2198 	setup->td.td_link = htole32(next->physaddr | UHCI_PTR_VF | UHCI_PTR_TD);
2199 	setup->td.td_status = htole32(UHCI_TD_SET_ERRCNT(3) | ls |
2200 		UHCI_TD_ACTIVE);
2201 	setup->td.td_token = htole32(UHCI_TD_SETUP(sizeof *req, endpt, addr));
2202 	setup->td.td_buffer = htole32(DMAADDR(&upipe->u.ctl.reqdma, 0));
2203 
2204 	stat->link.std = NULL;
2205 	stat->td.td_link = htole32(UHCI_PTR_T);
2206 	stat->td.td_status = htole32(UHCI_TD_SET_ERRCNT(3) | ls |
2207 		UHCI_TD_ACTIVE | UHCI_TD_IOC);
2208 	stat->td.td_token =
2209 		htole32(isread ? UHCI_TD_OUT(0, endpt, addr, 1) :
2210 		                 UHCI_TD_IN (0, endpt, addr, 1));
2211 	stat->td.td_buffer = htole32(0);
2212 
2213 #ifdef UHCI_DEBUG
2214 	if (uhcidebug > 10) {
2215 		DPRINTF(("uhci_device_request: before transfer\n"));
2216 		uhci_dump_tds(setup);
2217 	}
2218 #endif
2219 
2220 	/* Set up interrupt info. */
2221 	ii->xfer = xfer;
2222 	ii->stdstart = setup;
2223 	ii->stdend = stat;
2224 #ifdef DIAGNOSTIC
2225 	if (!ii->isdone) {
2226 		printf("uhci_device_request: not done, ii=%p\n", ii);
2227 	}
2228 	ii->isdone = 0;
2229 #endif
2230 
2231 	sqh->elink = setup;
2232 	sqh->qh.qh_elink = htole32(setup->physaddr | UHCI_PTR_TD);
2233 
2234 	s = splusb();
2235 	if (dev->speed == USB_SPEED_LOW)
2236 		uhci_add_ls_ctrl(sc, sqh);
2237 	else
2238 		uhci_add_hs_ctrl(sc, sqh);
2239 	uhci_add_intr_info(sc, ii);
2240 #ifdef UHCI_DEBUG
2241 	if (uhcidebug > 12) {
2242 		uhci_soft_td_t *std;
2243 		uhci_soft_qh_t *xqh;
2244 		uhci_soft_qh_t *sxqh;
2245 		int maxqh = 0;
2246 		uhci_physaddr_t link;
2247 		DPRINTF(("uhci_enter_ctl_q: follow from [0]\n"));
2248 		for (std = sc->sc_vframes[0].htd, link = 0;
2249 		     (link & UHCI_PTR_QH) == 0;
2250 		     std = std->link.std) {
2251 			link = le32toh(std->td.td_link);
2252 			uhci_dump_td(std);
2253 		}
2254 		sxqh = (uhci_soft_qh_t *)std;
2255 		uhci_dump_qh(sxqh);
2256 		for (xqh = sxqh;
2257 		     xqh != NULL;
2258 		     xqh = (maxqh++ == 5 || xqh->hlink == sxqh ||
2259                             xqh->hlink == xqh ? NULL : xqh->hlink)) {
2260 			uhci_dump_qh(xqh);
2261 		}
2262 		DPRINTF(("Enqueued QH:\n"));
2263 		uhci_dump_qh(sqh);
2264 		uhci_dump_tds(sqh->elink);
2265 	}
2266 #endif
2267 	if (xfer->timeout && !sc->sc_bus.use_polling) {
2268 		usb_callout(xfer->timeout_handle, MS_TO_TICKS(xfer->timeout),
2269 			    uhci_timeout, ii);
2270 	}
2271 	xfer->status = USBD_IN_PROGRESS;
2272 	splx(s);
2273 
2274 	return (USBD_NORMAL_COMPLETION);
2275 }
2276 
2277 usbd_status
2278 uhci_device_isoc_transfer(usbd_xfer_handle xfer)
2279 {
2280 	usbd_status err;
2281 
2282 	DPRINTFN(5,("uhci_device_isoc_transfer: xfer=%p\n", xfer));
2283 
2284 	/* Put it on our queue, */
2285 	err = usb_insert_transfer(xfer);
2286 
2287 	/* bail out on error, */
2288 	if (err && err != USBD_IN_PROGRESS)
2289 		return (err);
2290 
2291 	/* XXX should check inuse here */
2292 
2293 	/* insert into schedule, */
2294 	uhci_device_isoc_enter(xfer);
2295 
2296 	/* and start if the pipe wasn't running */
2297 	if (!err)
2298 		uhci_device_isoc_start(SIMPLEQ_FIRST(&xfer->pipe->queue));
2299 
2300 	return (err);
2301 }
2302 
2303 void
2304 uhci_device_isoc_enter(usbd_xfer_handle xfer)
2305 {
2306 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2307 	usbd_device_handle dev = upipe->pipe.device;
2308 	uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
2309 	struct iso *iso = &upipe->u.iso;
2310 	uhci_soft_td_t *std;
2311 	u_int32_t buf, len, status;
2312 	int s, i, next, nframes;
2313 
2314 	DPRINTFN(5,("uhci_device_isoc_enter: used=%d next=%d xfer=%p "
2315 		    "nframes=%d\n",
2316 		    iso->inuse, iso->next, xfer, xfer->nframes));
2317 
2318 	if (sc->sc_dying)
2319 		return;
2320 
2321 	if (xfer->status == USBD_IN_PROGRESS) {
2322 		/* This request has already been entered into the frame list */
2323 		printf("uhci_device_isoc_enter: xfer=%p in frame list\n", xfer);
2324 		/* XXX */
2325 	}
2326 
2327 #ifdef DIAGNOSTIC
2328 	if (iso->inuse >= UHCI_VFRAMELIST_COUNT)
2329 		printf("uhci_device_isoc_enter: overflow!\n");
2330 #endif
2331 
2332 	next = iso->next;
2333 	if (next == -1) {
2334 		/* Not in use yet, schedule it a few frames ahead. */
2335 		next = (UREAD2(sc, UHCI_FRNUM) + 3) % UHCI_VFRAMELIST_COUNT;
2336 		DPRINTFN(2,("uhci_device_isoc_enter: start next=%d\n", next));
2337 	}
2338 
2339 	xfer->status = USBD_IN_PROGRESS;
2340 	UXFER(xfer)->curframe = next;
2341 
2342 	buf = DMAADDR(&xfer->dmabuf, 0);
2343 	status = UHCI_TD_ZERO_ACTLEN(UHCI_TD_SET_ERRCNT(0) |
2344 				     UHCI_TD_ACTIVE |
2345 				     UHCI_TD_IOS);
2346 	nframes = xfer->nframes;
2347 	s = splusb();
2348 	for (i = 0; i < nframes; i++) {
2349 		std = iso->stds[next];
2350 		if (++next >= UHCI_VFRAMELIST_COUNT)
2351 			next = 0;
2352 		len = xfer->frlengths[i];
2353 		std->td.td_buffer = htole32(buf);
2354 		if (i == nframes - 1)
2355 			status |= UHCI_TD_IOC;
2356 		std->td.td_status = htole32(status);
2357 		std->td.td_token &= htole32(~UHCI_TD_MAXLEN_MASK);
2358 		std->td.td_token |= htole32(UHCI_TD_SET_MAXLEN(len));
2359 #ifdef UHCI_DEBUG
2360 		if (uhcidebug > 5) {
2361 			DPRINTFN(5,("uhci_device_isoc_enter: TD %d\n", i));
2362 			uhci_dump_td(std);
2363 		}
2364 #endif
2365 		buf += len;
2366 	}
2367 	iso->next = next;
2368 	iso->inuse += xfer->nframes;
2369 
2370 	splx(s);
2371 }
2372 
2373 usbd_status
2374 uhci_device_isoc_start(usbd_xfer_handle xfer)
2375 {
2376 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2377 	uhci_softc_t *sc = (uhci_softc_t *)upipe->pipe.device->bus;
2378 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
2379 	uhci_soft_td_t *end;
2380 	int s, i;
2381 
2382 	DPRINTFN(5,("uhci_device_isoc_start: xfer=%p\n", xfer));
2383 
2384 	if (sc->sc_dying)
2385 		return (USBD_IOERROR);
2386 
2387 #ifdef DIAGNOSTIC
2388 	if (xfer->status != USBD_IN_PROGRESS)
2389 		printf("uhci_device_isoc_start: not in progress %p\n", xfer);
2390 #endif
2391 
2392 	/* Find the last TD */
2393 	i = UXFER(xfer)->curframe + xfer->nframes;
2394 	if (i >= UHCI_VFRAMELIST_COUNT)
2395 		i -= UHCI_VFRAMELIST_COUNT;
2396 	end = upipe->u.iso.stds[i];
2397 
2398 #ifdef DIAGNOSTIC
2399 	if (end == NULL) {
2400 		printf("uhci_device_isoc_start: end == NULL\n");
2401 		return (USBD_INVAL);
2402 	}
2403 #endif
2404 
2405 	s = splusb();
2406 
2407 	/* Set up interrupt info. */
2408 	ii->xfer = xfer;
2409 	ii->stdstart = end;
2410 	ii->stdend = end;
2411 #ifdef DIAGNOSTIC
2412 	if (!ii->isdone)
2413 		printf("uhci_device_isoc_start: not done, ii=%p\n", ii);
2414 	ii->isdone = 0;
2415 #endif
2416 	uhci_add_intr_info(sc, ii);
2417 
2418 	splx(s);
2419 
2420 	return (USBD_IN_PROGRESS);
2421 }
2422 
2423 void
2424 uhci_device_isoc_abort(usbd_xfer_handle xfer)
2425 {
2426 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2427 	uhci_soft_td_t **stds = upipe->u.iso.stds;
2428 	uhci_soft_td_t *std;
2429 	int i, n, s, nframes, maxlen, len;
2430 
2431 	s = splusb();
2432 
2433 	/* Transfer is already done. */
2434 	if (xfer->status != USBD_NOT_STARTED &&
2435 	    xfer->status != USBD_IN_PROGRESS) {
2436 		splx(s);
2437 		return;
2438 	}
2439 
2440 	/* Give xfer the requested abort code. */
2441 	xfer->status = USBD_CANCELLED;
2442 
2443 	/* make hardware ignore it, */
2444 	nframes = xfer->nframes;
2445 	n = UXFER(xfer)->curframe;
2446 	maxlen = 0;
2447 	for (i = 0; i < nframes; i++) {
2448 		std = stds[n];
2449 		std->td.td_status &= htole32(~(UHCI_TD_ACTIVE | UHCI_TD_IOC));
2450 		len = UHCI_TD_GET_MAXLEN(le32toh(std->td.td_token));
2451 		if (len > maxlen)
2452 			maxlen = len;
2453 		if (++n >= UHCI_VFRAMELIST_COUNT)
2454 			n = 0;
2455 	}
2456 
2457 	/* and wait until we are sure the hardware has finished. */
2458 	delay(maxlen);
2459 
2460 #ifdef DIAGNOSTIC
2461 	UXFER(xfer)->iinfo.isdone = 1;
2462 #endif
2463 	/* Run callback and remove from interrupt list. */
2464 	usb_transfer_complete(xfer);
2465 
2466 	splx(s);
2467 }
2468 
2469 void
2470 uhci_device_isoc_close(usbd_pipe_handle pipe)
2471 {
2472 	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
2473 	usbd_device_handle dev = upipe->pipe.device;
2474 	uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
2475 	uhci_soft_td_t *std, *vstd;
2476 	struct iso *iso;
2477 	int i, s;
2478 
2479 	/*
2480 	 * Make sure all TDs are marked as inactive.
2481 	 * Wait for completion.
2482 	 * Unschedule.
2483 	 * Deallocate.
2484 	 */
2485 	iso = &upipe->u.iso;
2486 
2487 	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++)
2488 		iso->stds[i]->td.td_status &= htole32(~UHCI_TD_ACTIVE);
2489 	usb_delay_ms(&sc->sc_bus, 2); /* wait for completion */
2490 
2491 	s = splusb();
2492 	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
2493 		std = iso->stds[i];
2494 		for (vstd = sc->sc_vframes[i].htd;
2495 		     vstd != NULL && vstd->link.std != std;
2496 		     vstd = vstd->link.std)
2497 			;
2498 		if (vstd == NULL) {
2499 			/*panic*/
2500 			printf("uhci_device_isoc_close: %p not found\n", std);
2501 			splx(s);
2502 			return;
2503 		}
2504 		vstd->link = std->link;
2505 		vstd->td.td_link = std->td.td_link;
2506 		uhci_free_std(sc, std);
2507 	}
2508 	splx(s);
2509 
2510 	free(iso->stds, M_USBHC);
2511 }
2512 
2513 usbd_status
2514 uhci_setup_isoc(usbd_pipe_handle pipe)
2515 {
2516 	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
2517 	usbd_device_handle dev = upipe->pipe.device;
2518 	uhci_softc_t *sc = (uhci_softc_t *)dev->bus;
2519 	int addr = upipe->pipe.device->address;
2520 	int endpt = upipe->pipe.endpoint->edesc->bEndpointAddress;
2521 	int rd = UE_GET_DIR(endpt) == UE_DIR_IN;
2522 	uhci_soft_td_t *std, *vstd;
2523 	u_int32_t token;
2524 	struct iso *iso;
2525 	int i, s;
2526 
2527 	iso = &upipe->u.iso;
2528 	iso->stds = malloc(UHCI_VFRAMELIST_COUNT * sizeof (uhci_soft_td_t *),
2529 			   M_USBHC, M_WAITOK);
2530 
2531 	token = rd ? UHCI_TD_IN (0, endpt, addr, 0) :
2532 		     UHCI_TD_OUT(0, endpt, addr, 0);
2533 
2534 	/* Allocate the TDs and mark as inactive; */
2535 	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
2536 		std = uhci_alloc_std(sc);
2537 		if (std == 0)
2538 			goto bad;
2539 		std->td.td_status = htole32(UHCI_TD_IOS); /* iso, inactive */
2540 		std->td.td_token = htole32(token);
2541 		iso->stds[i] = std;
2542 	}
2543 
2544 	/* Insert TDs into schedule. */
2545 	s = splusb();
2546 	for (i = 0; i < UHCI_VFRAMELIST_COUNT; i++) {
2547 		std = iso->stds[i];
2548 		vstd = sc->sc_vframes[i].htd;
2549 		std->link = vstd->link;
2550 		std->td.td_link = vstd->td.td_link;
2551 		vstd->link.std = std;
2552 		vstd->td.td_link = htole32(std->physaddr | UHCI_PTR_TD);
2553 	}
2554 	splx(s);
2555 
2556 	iso->next = -1;
2557 	iso->inuse = 0;
2558 
2559 	return (USBD_NORMAL_COMPLETION);
2560 
2561  bad:
2562 	while (--i >= 0)
2563 		uhci_free_std(sc, iso->stds[i]);
2564 	free(iso->stds, M_USBHC);
2565 	return (USBD_NOMEM);
2566 }
2567 
2568 void
2569 uhci_device_isoc_done(usbd_xfer_handle xfer)
2570 {
2571 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
2572 
2573 	DPRINTFN(4, ("uhci_isoc_done: length=%d\n", xfer->actlen));
2574 
2575 	if (ii->xfer != xfer)
2576 		/* Not on interrupt list, ignore it. */
2577 		return;
2578 
2579 #ifdef DIAGNOSTIC
2580 	if (xfer->busy_free != XFER_BUSY) {
2581 		printf("uhci_device_isoc_done: xfer=%p not busy 0x%08x\n",
2582 		       xfer, xfer->busy_free);
2583 		return;
2584 	}
2585 
2586         if (ii->stdend == NULL) {
2587                 printf("uhci_device_isoc_done: xfer=%p stdend==NULL\n", xfer);
2588 #ifdef UHCI_DEBUG
2589 		uhci_dump_ii(ii);
2590 #endif
2591 		return;
2592 	}
2593 #endif
2594 
2595 	/* Turn off the interrupt since it is active even if the TD is not. */
2596 	ii->stdend->td.td_status &= htole32(~UHCI_TD_IOC);
2597 
2598 	uhci_del_intr_info(ii);	/* remove from active list */
2599 }
2600 
2601 void
2602 uhci_device_intr_done(usbd_xfer_handle xfer)
2603 {
2604 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
2605 	uhci_softc_t *sc = ii->sc;
2606 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2607 	uhci_soft_qh_t *sqh;
2608 	int i, npoll;
2609 
2610 	DPRINTFN(5, ("uhci_intr_done: length=%d\n", xfer->actlen));
2611 
2612 	npoll = upipe->u.intr.npoll;
2613 	for(i = 0; i < npoll; i++) {
2614 		sqh = upipe->u.intr.qhs[i];
2615 		sqh->elink = NULL;
2616 		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
2617 	}
2618 	uhci_free_std_chain(sc, ii->stdstart, NULL);
2619 
2620 	/* XXX Wasteful. */
2621 	if (xfer->pipe->repeat) {
2622 		uhci_soft_td_t *data, *dataend;
2623 
2624 		DPRINTFN(5,("uhci_device_intr_done: requeing\n"));
2625 
2626 		/* This alloc cannot fail since we freed the chain above. */
2627 		uhci_alloc_std_chain(upipe, sc, xfer->length, 1, xfer->flags,
2628 				     &xfer->dmabuf, &data, &dataend);
2629 		dataend->td.td_status |= htole32(UHCI_TD_IOC);
2630 
2631 #ifdef UHCI_DEBUG
2632 		if (uhcidebug > 10) {
2633 			DPRINTF(("uhci_device_intr_done: data(1)\n"));
2634 			uhci_dump_tds(data);
2635 			uhci_dump_qh(upipe->u.intr.qhs[0]);
2636 		}
2637 #endif
2638 
2639 		ii->stdstart = data;
2640 		ii->stdend = dataend;
2641 #ifdef DIAGNOSTIC
2642 		if (!ii->isdone) {
2643 			printf("uhci_device_intr_done: not done, ii=%p\n", ii);
2644 		}
2645 		ii->isdone = 0;
2646 #endif
2647 		for (i = 0; i < npoll; i++) {
2648 			sqh = upipe->u.intr.qhs[i];
2649 			sqh->elink = data;
2650 			sqh->qh.qh_elink = htole32(data->physaddr | UHCI_PTR_TD);
2651 		}
2652 		xfer->status = USBD_IN_PROGRESS;
2653 		/* The ii is already on the examined list, just leave it. */
2654 	} else {
2655 		DPRINTFN(5,("uhci_device_intr_done: removing\n"));
2656 		uhci_del_intr_info(ii);
2657 	}
2658 }
2659 
2660 /* Deallocate request data structures */
2661 void
2662 uhci_device_ctrl_done(usbd_xfer_handle xfer)
2663 {
2664 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
2665 	uhci_softc_t *sc = ii->sc;
2666 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2667 
2668 #ifdef DIAGNOSTIC
2669 	if (!(xfer->rqflags & URQ_REQUEST))
2670 		panic("uhci_ctrl_done: not a request\n");
2671 #endif
2672 
2673 	uhci_del_intr_info(ii);	/* remove from active list */
2674 
2675 	if (upipe->pipe.device->speed == USB_SPEED_LOW)
2676 		uhci_remove_ls_ctrl(sc, upipe->u.ctl.sqh);
2677 	else
2678 		uhci_remove_hs_ctrl(sc, upipe->u.ctl.sqh);
2679 
2680 	if (upipe->u.ctl.length != 0)
2681 		uhci_free_std_chain(sc, ii->stdstart->link.std, ii->stdend);
2682 
2683 	DPRINTFN(5, ("uhci_ctrl_done: length=%d\n", xfer->actlen));
2684 }
2685 
2686 /* Deallocate request data structures */
2687 void
2688 uhci_device_bulk_done(usbd_xfer_handle xfer)
2689 {
2690 	uhci_intr_info_t *ii = &UXFER(xfer)->iinfo;
2691 	uhci_softc_t *sc = ii->sc;
2692 	struct uhci_pipe *upipe = (struct uhci_pipe *)xfer->pipe;
2693 
2694 	uhci_del_intr_info(ii);	/* remove from active list */
2695 
2696 	uhci_remove_bulk(sc, upipe->u.bulk.sqh);
2697 
2698 	uhci_free_std_chain(sc, ii->stdstart, NULL);
2699 
2700 	DPRINTFN(5, ("uhci_bulk_done: length=%d\n", xfer->actlen));
2701 }
2702 
2703 /* Add interrupt QH, called with vflock. */
2704 void
2705 uhci_add_intr(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
2706 {
2707 	struct uhci_vframe *vf = &sc->sc_vframes[sqh->pos];
2708 	uhci_soft_qh_t *eqh;
2709 
2710 	DPRINTFN(4, ("uhci_add_intr: n=%d sqh=%p\n", sqh->pos, sqh));
2711 
2712 	eqh = vf->eqh;
2713 	sqh->hlink       = eqh->hlink;
2714 	sqh->qh.qh_hlink = eqh->qh.qh_hlink;
2715 	eqh->hlink       = sqh;
2716 	eqh->qh.qh_hlink = htole32(sqh->physaddr | UHCI_PTR_QH);
2717 	vf->eqh = sqh;
2718 	vf->bandwidth++;
2719 }
2720 
2721 /* Remove interrupt QH. */
2722 void
2723 uhci_remove_intr(uhci_softc_t *sc, uhci_soft_qh_t *sqh)
2724 {
2725 	struct uhci_vframe *vf = &sc->sc_vframes[sqh->pos];
2726 	uhci_soft_qh_t *pqh;
2727 
2728 	DPRINTFN(4, ("uhci_remove_intr: n=%d sqh=%p\n", sqh->pos, sqh));
2729 
2730 	/* See comment in uhci_remove_ctrl() */
2731 	if (!(sqh->qh.qh_elink & htole32(UHCI_PTR_T))) {
2732 		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
2733 		delay(UHCI_QH_REMOVE_DELAY);
2734 	}
2735 
2736 	pqh = uhci_find_prev_qh(vf->hqh, sqh);
2737 	pqh->hlink       = sqh->hlink;
2738 	pqh->qh.qh_hlink = sqh->qh.qh_hlink;
2739 	delay(UHCI_QH_REMOVE_DELAY);
2740 	if (vf->eqh == sqh)
2741 		vf->eqh = pqh;
2742 	vf->bandwidth--;
2743 }
2744 
2745 usbd_status
2746 uhci_device_setintr(uhci_softc_t *sc, struct uhci_pipe *upipe, int ival)
2747 {
2748 	uhci_soft_qh_t *sqh;
2749 	int i, npoll, s;
2750 	u_int bestbw, bw, bestoffs, offs;
2751 
2752 	DPRINTFN(2, ("uhci_setintr: pipe=%p\n", upipe));
2753 	if (ival == 0) {
2754 		printf("uhci_setintr: 0 interval\n");
2755 		return (USBD_INVAL);
2756 	}
2757 
2758 	if (ival > UHCI_VFRAMELIST_COUNT)
2759 		ival = UHCI_VFRAMELIST_COUNT;
2760 	npoll = (UHCI_VFRAMELIST_COUNT + ival - 1) / ival;
2761 	DPRINTFN(2, ("uhci_setintr: ival=%d npoll=%d\n", ival, npoll));
2762 
2763 	upipe->u.intr.npoll = npoll;
2764 	upipe->u.intr.qhs =
2765 		malloc(npoll * sizeof(uhci_soft_qh_t *), M_USBHC, M_WAITOK);
2766 
2767 	/*
2768 	 * Figure out which offset in the schedule that has most
2769 	 * bandwidth left over.
2770 	 */
2771 #define MOD(i) ((i) & (UHCI_VFRAMELIST_COUNT-1))
2772 	for (bestoffs = offs = 0, bestbw = ~0; offs < ival; offs++) {
2773 		for (bw = i = 0; i < npoll; i++)
2774 			bw += sc->sc_vframes[MOD(i * ival + offs)].bandwidth;
2775 		if (bw < bestbw) {
2776 			bestbw = bw;
2777 			bestoffs = offs;
2778 		}
2779 	}
2780 	DPRINTFN(1, ("uhci_setintr: bw=%d offs=%d\n", bestbw, bestoffs));
2781 
2782 	for(i = 0; i < npoll; i++) {
2783 		upipe->u.intr.qhs[i] = sqh = uhci_alloc_sqh(sc);
2784 		sqh->elink = NULL;
2785 		sqh->qh.qh_elink = htole32(UHCI_PTR_T);
2786 		sqh->pos = MOD(i * ival + bestoffs);
2787 	}
2788 #undef MOD
2789 
2790 	s = splusb();
2791 	/* Enter QHs into the controller data structures. */
2792 	for(i = 0; i < npoll; i++)
2793 		uhci_add_intr(sc, upipe->u.intr.qhs[i]);
2794 	splx(s);
2795 
2796 	DPRINTFN(5, ("uhci_setintr: returns %p\n", upipe));
2797 	return (USBD_NORMAL_COMPLETION);
2798 }
2799 
2800 /* Open a new pipe. */
2801 usbd_status
2802 uhci_open(usbd_pipe_handle pipe)
2803 {
2804 	uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
2805 	struct uhci_pipe *upipe = (struct uhci_pipe *)pipe;
2806 	usb_endpoint_descriptor_t *ed = pipe->endpoint->edesc;
2807 	usbd_status err;
2808 	int ival;
2809 
2810 	DPRINTFN(1, ("uhci_open: pipe=%p, addr=%d, endpt=%d (%d)\n",
2811 		     pipe, pipe->device->address,
2812 		     ed->bEndpointAddress, sc->sc_addr));
2813 
2814 	upipe->aborting = 0;
2815 	upipe->nexttoggle = 0;
2816 
2817 	if (pipe->device->address == sc->sc_addr) {
2818 		switch (ed->bEndpointAddress) {
2819 		case USB_CONTROL_ENDPOINT:
2820 			pipe->methods = &uhci_root_ctrl_methods;
2821 			break;
2822 		case UE_DIR_IN | UHCI_INTR_ENDPT:
2823 			pipe->methods = &uhci_root_intr_methods;
2824 			break;
2825 		default:
2826 			return (USBD_INVAL);
2827 		}
2828 	} else {
2829 		switch (ed->bmAttributes & UE_XFERTYPE) {
2830 		case UE_CONTROL:
2831 			pipe->methods = &uhci_device_ctrl_methods;
2832 			upipe->u.ctl.sqh = uhci_alloc_sqh(sc);
2833 			if (upipe->u.ctl.sqh == NULL)
2834 				goto bad;
2835 			upipe->u.ctl.setup = uhci_alloc_std(sc);
2836 			if (upipe->u.ctl.setup == NULL) {
2837 				uhci_free_sqh(sc, upipe->u.ctl.sqh);
2838 				goto bad;
2839 			}
2840 			upipe->u.ctl.stat = uhci_alloc_std(sc);
2841 			if (upipe->u.ctl.stat == NULL) {
2842 				uhci_free_sqh(sc, upipe->u.ctl.sqh);
2843 				uhci_free_std(sc, upipe->u.ctl.setup);
2844 				goto bad;
2845 			}
2846 			err = usb_allocmem(&sc->sc_bus,
2847 				  sizeof(usb_device_request_t),
2848 				  0, &upipe->u.ctl.reqdma);
2849 			if (err) {
2850 				uhci_free_sqh(sc, upipe->u.ctl.sqh);
2851 				uhci_free_std(sc, upipe->u.ctl.setup);
2852 				uhci_free_std(sc, upipe->u.ctl.stat);
2853 				goto bad;
2854 			}
2855 			break;
2856 		case UE_INTERRUPT:
2857 			pipe->methods = &uhci_device_intr_methods;
2858 			ival = pipe->interval;
2859 			if (ival == USBD_DEFAULT_INTERVAL)
2860 				ival = ed->bInterval;
2861 			return (uhci_device_setintr(sc, upipe, ival));
2862 		case UE_ISOCHRONOUS:
2863 			pipe->methods = &uhci_device_isoc_methods;
2864 			return (uhci_setup_isoc(pipe));
2865 		case UE_BULK:
2866 			pipe->methods = &uhci_device_bulk_methods;
2867 			upipe->u.bulk.sqh = uhci_alloc_sqh(sc);
2868 			if (upipe->u.bulk.sqh == NULL)
2869 				goto bad;
2870 			break;
2871 		}
2872 	}
2873 	return (USBD_NORMAL_COMPLETION);
2874 
2875  bad:
2876 	return (USBD_NOMEM);
2877 }
2878 
2879 /*
2880  * Data structures and routines to emulate the root hub.
2881  */
2882 usb_device_descriptor_t uhci_devd = {
2883 	USB_DEVICE_DESCRIPTOR_SIZE,
2884 	UDESC_DEVICE,		/* type */
2885 	{0x00, 0x01},		/* USB version */
2886 	UDCLASS_HUB,		/* class */
2887 	UDSUBCLASS_HUB,		/* subclass */
2888 	UDPROTO_FSHUB,		/* protocol */
2889 	64,			/* max packet */
2890 	{0},{0},{0x00,0x01},	/* device id */
2891 	1,2,0,			/* string indicies */
2892 	1			/* # of configurations */
2893 };
2894 
2895 usb_config_descriptor_t uhci_confd = {
2896 	USB_CONFIG_DESCRIPTOR_SIZE,
2897 	UDESC_CONFIG,
2898 	{USB_CONFIG_DESCRIPTOR_SIZE +
2899 	 USB_INTERFACE_DESCRIPTOR_SIZE +
2900 	 USB_ENDPOINT_DESCRIPTOR_SIZE},
2901 	1,
2902 	1,
2903 	0,
2904 	UC_SELF_POWERED,
2905 	0			/* max power */
2906 };
2907 
2908 usb_interface_descriptor_t uhci_ifcd = {
2909 	USB_INTERFACE_DESCRIPTOR_SIZE,
2910 	UDESC_INTERFACE,
2911 	0,
2912 	0,
2913 	1,
2914 	UICLASS_HUB,
2915 	UISUBCLASS_HUB,
2916 	UIPROTO_FSHUB,
2917 	0
2918 };
2919 
2920 usb_endpoint_descriptor_t uhci_endpd = {
2921 	USB_ENDPOINT_DESCRIPTOR_SIZE,
2922 	UDESC_ENDPOINT,
2923 	UE_DIR_IN | UHCI_INTR_ENDPT,
2924 	UE_INTERRUPT,
2925 	{8},
2926 	255
2927 };
2928 
2929 usb_hub_descriptor_t uhci_hubd_piix = {
2930 	USB_HUB_DESCRIPTOR_SIZE,
2931 	UDESC_HUB,
2932 	2,
2933 	{ UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL, 0 },
2934 	50,			/* power on to power good */
2935 	0,
2936 	{ 0x00 },		/* both ports are removable */
2937 };
2938 
2939 int
2940 uhci_str(usb_string_descriptor_t *p, int l, char *s)
2941 {
2942 	int i;
2943 
2944 	if (l == 0)
2945 		return (0);
2946 	p->bLength = 2 * strlen(s) + 2;
2947 	if (l == 1)
2948 		return (1);
2949 	p->bDescriptorType = UDESC_STRING;
2950 	l -= 2;
2951 	for (i = 0; s[i] && l > 1; i++, l -= 2)
2952 		USETW2(p->bString[i], 0, s[i]);
2953 	return (2*i+2);
2954 }
2955 
2956 /*
2957  * Simulate a hardware hub by handling all the necessary requests.
2958  */
2959 usbd_status
2960 uhci_root_ctrl_transfer(usbd_xfer_handle xfer)
2961 {
2962 	usbd_status err;
2963 
2964 	/* Insert last in queue. */
2965 	err = usb_insert_transfer(xfer);
2966 	if (err)
2967 		return (err);
2968 
2969 	/*
2970 	 * Pipe isn't running (otherwise err would be USBD_INPROG),
2971 	 * so start it first.
2972 	 */
2973 	return (uhci_root_ctrl_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
2974 }
2975 
2976 usbd_status
2977 uhci_root_ctrl_start(usbd_xfer_handle xfer)
2978 {
2979 	uhci_softc_t *sc = (uhci_softc_t *)xfer->pipe->device->bus;
2980 	usb_device_request_t *req;
2981 	void *buf = NULL;
2982 	int port, x;
2983 	int s, len, value, index, status, change, l, totlen = 0;
2984 	usb_port_status_t ps;
2985 	usbd_status err;
2986 
2987 	if (sc->sc_dying)
2988 		return (USBD_IOERROR);
2989 
2990 #ifdef DIAGNOSTIC
2991 	if (!(xfer->rqflags & URQ_REQUEST))
2992 		panic("uhci_root_ctrl_transfer: not a request\n");
2993 #endif
2994 	req = &xfer->request;
2995 
2996 	DPRINTFN(2,("uhci_root_ctrl_control type=0x%02x request=%02x\n",
2997 		    req->bmRequestType, req->bRequest));
2998 
2999 	len = UGETW(req->wLength);
3000 	value = UGETW(req->wValue);
3001 	index = UGETW(req->wIndex);
3002 
3003 	if (len != 0)
3004 		buf = KERNADDR(&xfer->dmabuf, 0);
3005 
3006 #define C(x,y) ((x) | ((y) << 8))
3007 	switch(C(req->bRequest, req->bmRequestType)) {
3008 	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
3009 	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
3010 	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
3011 		/*
3012 		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
3013 		 * for the integrated root hub.
3014 		 */
3015 		break;
3016 	case C(UR_GET_CONFIG, UT_READ_DEVICE):
3017 		if (len > 0) {
3018 			*(u_int8_t *)buf = sc->sc_conf;
3019 			totlen = 1;
3020 		}
3021 		break;
3022 	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
3023 		DPRINTFN(2,("uhci_root_ctrl_control wValue=0x%04x\n", value));
3024 		switch(value >> 8) {
3025 		case UDESC_DEVICE:
3026 			if ((value & 0xff) != 0) {
3027 				err = USBD_IOERROR;
3028 				goto ret;
3029 			}
3030 			totlen = l = min(len, USB_DEVICE_DESCRIPTOR_SIZE);
3031 			USETW(uhci_devd.idVendor, sc->sc_id_vendor);
3032 			memcpy(buf, &uhci_devd, l);
3033 			break;
3034 		case UDESC_CONFIG:
3035 			if ((value & 0xff) != 0) {
3036 				err = USBD_IOERROR;
3037 				goto ret;
3038 			}
3039 			totlen = l = min(len, USB_CONFIG_DESCRIPTOR_SIZE);
3040 			memcpy(buf, &uhci_confd, l);
3041 			buf = (char *)buf + l;
3042 			len -= l;
3043 			l = min(len, USB_INTERFACE_DESCRIPTOR_SIZE);
3044 			totlen += l;
3045 			memcpy(buf, &uhci_ifcd, l);
3046 			buf = (char *)buf + l;
3047 			len -= l;
3048 			l = min(len, USB_ENDPOINT_DESCRIPTOR_SIZE);
3049 			totlen += l;
3050 			memcpy(buf, &uhci_endpd, l);
3051 			break;
3052 		case UDESC_STRING:
3053 			if (len == 0)
3054 				break;
3055 			*(u_int8_t *)buf = 0;
3056 			totlen = 1;
3057 			switch (value & 0xff) {
3058 			case 1: /* Vendor */
3059 				totlen = uhci_str(buf, len, sc->sc_vendor);
3060 				break;
3061 			case 2: /* Product */
3062 				totlen = uhci_str(buf, len, "UHCI root hub");
3063 				break;
3064 			}
3065 			break;
3066 		default:
3067 			err = USBD_IOERROR;
3068 			goto ret;
3069 		}
3070 		break;
3071 	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
3072 		if (len > 0) {
3073 			*(u_int8_t *)buf = 0;
3074 			totlen = 1;
3075 		}
3076 		break;
3077 	case C(UR_GET_STATUS, UT_READ_DEVICE):
3078 		if (len > 1) {
3079 			USETW(((usb_status_t *)buf)->wStatus,UDS_SELF_POWERED);
3080 			totlen = 2;
3081 		}
3082 		break;
3083 	case C(UR_GET_STATUS, UT_READ_INTERFACE):
3084 	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
3085 		if (len > 1) {
3086 			USETW(((usb_status_t *)buf)->wStatus, 0);
3087 			totlen = 2;
3088 		}
3089 		break;
3090 	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
3091 		if (value >= USB_MAX_DEVICES) {
3092 			err = USBD_IOERROR;
3093 			goto ret;
3094 		}
3095 		sc->sc_addr = value;
3096 		break;
3097 	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
3098 		if (value != 0 && value != 1) {
3099 			err = USBD_IOERROR;
3100 			goto ret;
3101 		}
3102 		sc->sc_conf = value;
3103 		break;
3104 	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
3105 		break;
3106 	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
3107 	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
3108 	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
3109 		err = USBD_IOERROR;
3110 		goto ret;
3111 	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
3112 		break;
3113 	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
3114 		break;
3115 	/* Hub requests */
3116 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
3117 		break;
3118 	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
3119 		DPRINTFN(3, ("uhci_root_ctrl_control: UR_CLEAR_PORT_FEATURE "
3120 			     "port=%d feature=%d\n",
3121 			     index, value));
3122 		if (index == 1)
3123 			port = UHCI_PORTSC1;
3124 		else if (index == 2)
3125 			port = UHCI_PORTSC2;
3126 		else {
3127 			err = USBD_IOERROR;
3128 			goto ret;
3129 		}
3130 		switch(value) {
3131 		case UHF_PORT_ENABLE:
3132 			x = URWMASK(UREAD2(sc, port));
3133 			UWRITE2(sc, port, x & ~UHCI_PORTSC_PE);
3134 			break;
3135 		case UHF_PORT_SUSPEND:
3136 			x = URWMASK(UREAD2(sc, port));
3137 			UWRITE2(sc, port, x & ~UHCI_PORTSC_SUSP);
3138 			break;
3139 		case UHF_PORT_RESET:
3140 			x = URWMASK(UREAD2(sc, port));
3141 			UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
3142 			break;
3143 		case UHF_C_PORT_CONNECTION:
3144 			x = URWMASK(UREAD2(sc, port));
3145 			UWRITE2(sc, port, x | UHCI_PORTSC_CSC);
3146 			break;
3147 		case UHF_C_PORT_ENABLE:
3148 			x = URWMASK(UREAD2(sc, port));
3149 			UWRITE2(sc, port, x | UHCI_PORTSC_POEDC);
3150 			break;
3151 		case UHF_C_PORT_OVER_CURRENT:
3152 			x = URWMASK(UREAD2(sc, port));
3153 			UWRITE2(sc, port, x | UHCI_PORTSC_OCIC);
3154 			break;
3155 		case UHF_C_PORT_RESET:
3156 			sc->sc_isreset = 0;
3157 			err = USBD_NORMAL_COMPLETION;
3158 			goto ret;
3159 		case UHF_PORT_CONNECTION:
3160 		case UHF_PORT_OVER_CURRENT:
3161 		case UHF_PORT_POWER:
3162 		case UHF_PORT_LOW_SPEED:
3163 		case UHF_C_PORT_SUSPEND:
3164 		default:
3165 			err = USBD_IOERROR;
3166 			goto ret;
3167 		}
3168 		break;
3169 	case C(UR_GET_BUS_STATE, UT_READ_CLASS_OTHER):
3170 		if (index == 1)
3171 			port = UHCI_PORTSC1;
3172 		else if (index == 2)
3173 			port = UHCI_PORTSC2;
3174 		else {
3175 			err = USBD_IOERROR;
3176 			goto ret;
3177 		}
3178 		if (len > 0) {
3179 			*(u_int8_t *)buf =
3180 				(UREAD2(sc, port) & UHCI_PORTSC_LS) >>
3181 				UHCI_PORTSC_LS_SHIFT;
3182 			totlen = 1;
3183 		}
3184 		break;
3185 	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
3186 		if (value != 0) {
3187 			err = USBD_IOERROR;
3188 			goto ret;
3189 		}
3190 		l = min(len, USB_HUB_DESCRIPTOR_SIZE);
3191 		totlen = l;
3192 		memcpy(buf, &uhci_hubd_piix, l);
3193 		break;
3194 	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
3195 		if (len != 4) {
3196 			err = USBD_IOERROR;
3197 			goto ret;
3198 		}
3199 		memset(buf, 0, len);
3200 		totlen = len;
3201 		break;
3202 	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
3203 		if (index == 1)
3204 			port = UHCI_PORTSC1;
3205 		else if (index == 2)
3206 			port = UHCI_PORTSC2;
3207 		else {
3208 			err = USBD_IOERROR;
3209 			goto ret;
3210 		}
3211 		if (len != 4) {
3212 			err = USBD_IOERROR;
3213 			goto ret;
3214 		}
3215 		x = UREAD2(sc, port);
3216 		status = change = 0;
3217 		if (x & UHCI_PORTSC_CCS)
3218 			status |= UPS_CURRENT_CONNECT_STATUS;
3219 		if (x & UHCI_PORTSC_CSC)
3220 			change |= UPS_C_CONNECT_STATUS;
3221 		if (x & UHCI_PORTSC_PE)
3222 			status |= UPS_PORT_ENABLED;
3223 		if (x & UHCI_PORTSC_POEDC)
3224 			change |= UPS_C_PORT_ENABLED;
3225 		if (x & UHCI_PORTSC_OCI)
3226 			status |= UPS_OVERCURRENT_INDICATOR;
3227 		if (x & UHCI_PORTSC_OCIC)
3228 			change |= UPS_C_OVERCURRENT_INDICATOR;
3229 		if (x & UHCI_PORTSC_SUSP)
3230 			status |= UPS_SUSPEND;
3231 		if (x & UHCI_PORTSC_LSDA)
3232 			status |= UPS_LOW_SPEED;
3233 		status |= UPS_PORT_POWER;
3234 		if (sc->sc_isreset)
3235 			change |= UPS_C_PORT_RESET;
3236 		USETW(ps.wPortStatus, status);
3237 		USETW(ps.wPortChange, change);
3238 		l = min(len, sizeof ps);
3239 		memcpy(buf, &ps, l);
3240 		totlen = l;
3241 		break;
3242 	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
3243 		err = USBD_IOERROR;
3244 		goto ret;
3245 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
3246 		break;
3247 	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
3248 		if (index == 1)
3249 			port = UHCI_PORTSC1;
3250 		else if (index == 2)
3251 			port = UHCI_PORTSC2;
3252 		else {
3253 			err = USBD_IOERROR;
3254 			goto ret;
3255 		}
3256 		switch(value) {
3257 		case UHF_PORT_ENABLE:
3258 			x = URWMASK(UREAD2(sc, port));
3259 			UWRITE2(sc, port, x | UHCI_PORTSC_PE);
3260 			break;
3261 		case UHF_PORT_SUSPEND:
3262 			x = URWMASK(UREAD2(sc, port));
3263 			UWRITE2(sc, port, x | UHCI_PORTSC_SUSP);
3264 			break;
3265 		case UHF_PORT_RESET:
3266 			x = URWMASK(UREAD2(sc, port));
3267 			UWRITE2(sc, port, x | UHCI_PORTSC_PR);
3268 			usb_delay_ms(&sc->sc_bus, USB_PORT_ROOT_RESET_DELAY);
3269 			UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
3270 			delay(100);
3271 			x = UREAD2(sc, port);
3272 			UWRITE2(sc, port, x  | UHCI_PORTSC_PE);
3273 			usb_delay_ms(&sc->sc_bus, 10); /* XXX */
3274 			DPRINTFN(3,("uhci port %d reset, status = 0x%04x\n",
3275 				    index, UREAD2(sc, port)));
3276 			sc->sc_isreset = 1;
3277 			break;
3278 		case UHF_PORT_POWER:
3279 			/* Pretend we turned on power */
3280 			err = USBD_NORMAL_COMPLETION;
3281 			goto ret;
3282 		case UHF_C_PORT_CONNECTION:
3283 		case UHF_C_PORT_ENABLE:
3284 		case UHF_C_PORT_OVER_CURRENT:
3285 		case UHF_PORT_CONNECTION:
3286 		case UHF_PORT_OVER_CURRENT:
3287 		case UHF_PORT_LOW_SPEED:
3288 		case UHF_C_PORT_SUSPEND:
3289 		case UHF_C_PORT_RESET:
3290 		default:
3291 			err = USBD_IOERROR;
3292 			goto ret;
3293 		}
3294 		break;
3295 	default:
3296 		err = USBD_IOERROR;
3297 		goto ret;
3298 	}
3299 	xfer->actlen = totlen;
3300 	err = USBD_NORMAL_COMPLETION;
3301  ret:
3302 	xfer->status = err;
3303 	s = splusb();
3304 	usb_transfer_complete(xfer);
3305 	splx(s);
3306 	return (USBD_IN_PROGRESS);
3307 }
3308 
3309 /* Abort a root control request. */
3310 void
3311 uhci_root_ctrl_abort(usbd_xfer_handle xfer)
3312 {
3313 	/* Nothing to do, all transfers are synchronous. */
3314 }
3315 
3316 /* Close the root pipe. */
3317 void
3318 uhci_root_ctrl_close(usbd_pipe_handle pipe)
3319 {
3320 	DPRINTF(("uhci_root_ctrl_close\n"));
3321 }
3322 
3323 /* Abort a root interrupt request. */
3324 void
3325 uhci_root_intr_abort(usbd_xfer_handle xfer)
3326 {
3327 	uhci_softc_t *sc = (uhci_softc_t *)xfer->pipe->device->bus;
3328 
3329 	usb_uncallout(sc->sc_poll_handle, uhci_poll_hub, xfer);
3330 	sc->sc_intr_xfer = NULL;
3331 
3332 	if (xfer->pipe->intrxfer == xfer) {
3333 		DPRINTF(("uhci_root_intr_abort: remove\n"));
3334 		xfer->pipe->intrxfer = 0;
3335 	}
3336 	xfer->status = USBD_CANCELLED;
3337 #ifdef DIAGNOSTIC
3338 	UXFER(xfer)->iinfo.isdone = 1;
3339 #endif
3340 	usb_transfer_complete(xfer);
3341 }
3342 
3343 usbd_status
3344 uhci_root_intr_transfer(usbd_xfer_handle xfer)
3345 {
3346 	usbd_status err;
3347 
3348 	/* Insert last in queue. */
3349 	err = usb_insert_transfer(xfer);
3350 	if (err)
3351 		return (err);
3352 
3353 	/* Pipe isn't running (otherwise err would be USBD_INPROG),
3354 	 * start first
3355 	 */
3356 	return (uhci_root_intr_start(SIMPLEQ_FIRST(&xfer->pipe->queue)));
3357 }
3358 
3359 /* Start a transfer on the root interrupt pipe */
3360 usbd_status
3361 uhci_root_intr_start(usbd_xfer_handle xfer)
3362 {
3363 	usbd_pipe_handle pipe = xfer->pipe;
3364 	uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
3365 
3366 	DPRINTFN(3, ("uhci_root_intr_transfer: xfer=%p len=%d flags=%d\n",
3367 		     xfer, xfer->length, xfer->flags));
3368 
3369 	if (sc->sc_dying)
3370 		return (USBD_IOERROR);
3371 
3372 	sc->sc_ival = MS_TO_TICKS(xfer->pipe->endpoint->edesc->bInterval);
3373 	usb_callout(sc->sc_poll_handle, sc->sc_ival, uhci_poll_hub, xfer);
3374 	sc->sc_intr_xfer = xfer;
3375 	return (USBD_IN_PROGRESS);
3376 }
3377 
3378 /* Close the root interrupt pipe. */
3379 void
3380 uhci_root_intr_close(usbd_pipe_handle pipe)
3381 {
3382 	uhci_softc_t *sc = (uhci_softc_t *)pipe->device->bus;
3383 
3384 	usb_uncallout(sc->sc_poll_handle, uhci_poll_hub, sc->sc_intr_xfer);
3385 	sc->sc_intr_xfer = NULL;
3386 	DPRINTF(("uhci_root_intr_close\n"));
3387 }
3388