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