1/* $FreeBSD$ */
2/*-
3 * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
4 * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
5 * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29/*
30 * USB Universal Host Controller driver.
31 * Handles e.g. PIIX3 and PIIX4.
32 *
33 * UHCI spec: http://developer.intel.com/design/USB/UHCI11D.htm
34 * USB spec:  http://www.usb.org/developers/docs/usbspec.zip
35 * PIIXn spec: ftp://download.intel.com/design/intarch/datashts/29055002.pdf
36 *             ftp://download.intel.com/design/intarch/datashts/29056201.pdf
37 */
38
39#ifdef USB_GLOBAL_INCLUDE_FILE
40#include USB_GLOBAL_INCLUDE_FILE
41#else
42#include <sys/stdint.h>
43#include <sys/stddef.h>
44#include <sys/param.h>
45#include <sys/queue.h>
46#include <sys/types.h>
47#include <sys/systm.h>
48#include <sys/kernel.h>
49#include <sys/bus.h>
50#include <sys/module.h>
51#include <sys/lock.h>
52#include <sys/mutex.h>
53#include <sys/condvar.h>
54#include <sys/sysctl.h>
55#include <sys/sx.h>
56#include <sys/unistd.h>
57#include <sys/callout.h>
58#include <sys/malloc.h>
59#include <sys/priv.h>
60
61#include <dev/usb/usb.h>
62#include <dev/usb/usbdi.h>
63
64#define	USB_DEBUG_VAR uhcidebug
65
66#include <dev/usb/usb_core.h>
67#include <dev/usb/usb_debug.h>
68#include <dev/usb/usb_busdma.h>
69#include <dev/usb/usb_process.h>
70#include <dev/usb/usb_transfer.h>
71#include <dev/usb/usb_device.h>
72#include <dev/usb/usb_hub.h>
73#include <dev/usb/usb_util.h>
74
75#include <dev/usb/usb_controller.h>
76#include <dev/usb/usb_bus.h>
77#endif			/* USB_GLOBAL_INCLUDE_FILE */
78
79#include <dev/usb/controller/uhci.h>
80#include <dev/usb/controller/uhcireg.h>
81
82#define	alt_next next
83#define	UHCI_BUS2SC(bus) \
84   ((uhci_softc_t *)(((uint8_t *)(bus)) - \
85    ((uint8_t *)&(((uhci_softc_t *)0)->sc_bus))))
86
87#ifdef USB_DEBUG
88static int uhcidebug = 0;
89static int uhcinoloop = 0;
90
91static SYSCTL_NODE(_hw_usb, OID_AUTO, uhci, CTLFLAG_RW, 0, "USB uhci");
92SYSCTL_INT(_hw_usb_uhci, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_TUN,
93    &uhcidebug, 0, "uhci debug level");
94TUNABLE_INT("hw.usb.uhci.debug", &uhcidebug);
95SYSCTL_INT(_hw_usb_uhci, OID_AUTO, loop, CTLFLAG_RW | CTLFLAG_TUN,
96    &uhcinoloop, 0, "uhci noloop");
97TUNABLE_INT("hw.usb.uhci.loop", &uhcinoloop);
98
99static void uhci_dumpregs(uhci_softc_t *sc);
100static void uhci_dump_tds(uhci_td_t *td);
101
102#endif
103
104#define	UBARR(sc) bus_space_barrier((sc)->sc_io_tag, (sc)->sc_io_hdl, 0, (sc)->sc_io_size, \
105			BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE)
106#define	UWRITE1(sc, r, x) \
107 do { UBARR(sc); bus_space_write_1((sc)->sc_io_tag, (sc)->sc_io_hdl, (r), (x)); \
108 } while (/*CONSTCOND*/0)
109#define	UWRITE2(sc, r, x) \
110 do { UBARR(sc); bus_space_write_2((sc)->sc_io_tag, (sc)->sc_io_hdl, (r), (x)); \
111 } while (/*CONSTCOND*/0)
112#define	UWRITE4(sc, r, x) \
113 do { UBARR(sc); bus_space_write_4((sc)->sc_io_tag, (sc)->sc_io_hdl, (r), (x)); \
114 } while (/*CONSTCOND*/0)
115#define	UREAD1(sc, r) (UBARR(sc), bus_space_read_1((sc)->sc_io_tag, (sc)->sc_io_hdl, (r)))
116#define	UREAD2(sc, r) (UBARR(sc), bus_space_read_2((sc)->sc_io_tag, (sc)->sc_io_hdl, (r)))
117#define	UREAD4(sc, r) (UBARR(sc), bus_space_read_4((sc)->sc_io_tag, (sc)->sc_io_hdl, (r)))
118
119#define	UHCICMD(sc, cmd) UWRITE2(sc, UHCI_CMD, cmd)
120#define	UHCISTS(sc) UREAD2(sc, UHCI_STS)
121
122#define	UHCI_RESET_TIMEOUT 100		/* ms, reset timeout */
123
124#define	UHCI_INTR_ENDPT 1
125
126struct uhci_mem_layout {
127
128	struct usb_page_search buf_res;
129	struct usb_page_search fix_res;
130
131	struct usb_page_cache *buf_pc;
132	struct usb_page_cache *fix_pc;
133
134	uint32_t buf_offset;
135
136	uint16_t max_frame_size;
137};
138
139struct uhci_std_temp {
140
141	struct uhci_mem_layout ml;
142	uhci_td_t *td;
143	uhci_td_t *td_next;
144	uint32_t average;
145	uint32_t td_status;
146	uint32_t td_token;
147	uint32_t len;
148	uint16_t max_frame_size;
149	uint8_t	shortpkt;
150	uint8_t	setup_alt_next;
151	uint8_t	last_frame;
152};
153
154extern struct usb_bus_methods uhci_bus_methods;
155extern struct usb_pipe_methods uhci_device_bulk_methods;
156extern struct usb_pipe_methods uhci_device_ctrl_methods;
157extern struct usb_pipe_methods uhci_device_intr_methods;
158extern struct usb_pipe_methods uhci_device_isoc_methods;
159
160static uint8_t	uhci_restart(uhci_softc_t *sc);
161static void	uhci_do_poll(struct usb_bus *);
162static void	uhci_device_done(struct usb_xfer *, usb_error_t);
163static void	uhci_transfer_intr_enqueue(struct usb_xfer *);
164static void	uhci_timeout(void *);
165static uint8_t	uhci_check_transfer(struct usb_xfer *);
166static void	uhci_root_intr(uhci_softc_t *sc);
167
168void
169uhci_iterate_hw_softc(struct usb_bus *bus, usb_bus_mem_sub_cb_t *cb)
170{
171	struct uhci_softc *sc = UHCI_BUS2SC(bus);
172	uint32_t i;
173
174	cb(bus, &sc->sc_hw.pframes_pc, &sc->sc_hw.pframes_pg,
175	    sizeof(uint32_t) * UHCI_FRAMELIST_COUNT, UHCI_FRAMELIST_ALIGN);
176
177	cb(bus, &sc->sc_hw.ls_ctl_start_pc, &sc->sc_hw.ls_ctl_start_pg,
178	    sizeof(uhci_qh_t), UHCI_QH_ALIGN);
179
180	cb(bus, &sc->sc_hw.fs_ctl_start_pc, &sc->sc_hw.fs_ctl_start_pg,
181	    sizeof(uhci_qh_t), UHCI_QH_ALIGN);
182
183	cb(bus, &sc->sc_hw.bulk_start_pc, &sc->sc_hw.bulk_start_pg,
184	    sizeof(uhci_qh_t), UHCI_QH_ALIGN);
185
186	cb(bus, &sc->sc_hw.last_qh_pc, &sc->sc_hw.last_qh_pg,
187	    sizeof(uhci_qh_t), UHCI_QH_ALIGN);
188
189	cb(bus, &sc->sc_hw.last_td_pc, &sc->sc_hw.last_td_pg,
190	    sizeof(uhci_td_t), UHCI_TD_ALIGN);
191
192	for (i = 0; i != UHCI_VFRAMELIST_COUNT; i++) {
193		cb(bus, sc->sc_hw.isoc_start_pc + i,
194		    sc->sc_hw.isoc_start_pg + i,
195		    sizeof(uhci_td_t), UHCI_TD_ALIGN);
196	}
197
198	for (i = 0; i != UHCI_IFRAMELIST_COUNT; i++) {
199		cb(bus, sc->sc_hw.intr_start_pc + i,
200		    sc->sc_hw.intr_start_pg + i,
201		    sizeof(uhci_qh_t), UHCI_QH_ALIGN);
202	}
203}
204
205static void
206uhci_mem_layout_init(struct uhci_mem_layout *ml, struct usb_xfer *xfer)
207{
208	ml->buf_pc = xfer->frbuffers + 0;
209	ml->fix_pc = xfer->buf_fixup;
210
211	ml->buf_offset = 0;
212
213	ml->max_frame_size = xfer->max_frame_size;
214}
215
216static void
217uhci_mem_layout_fixup(struct uhci_mem_layout *ml, struct uhci_td *td)
218{
219	usbd_get_page(ml->buf_pc, ml->buf_offset, &ml->buf_res);
220
221	if (ml->buf_res.length < td->len) {
222
223		/* need to do a fixup */
224
225		usbd_get_page(ml->fix_pc, 0, &ml->fix_res);
226
227		td->td_buffer = htole32(ml->fix_res.physaddr);
228
229		/*
230	         * The UHCI driver cannot handle
231	         * page crossings, so a fixup is
232	         * needed:
233	         *
234	         *  +----+----+ - - -
235	         *  | YYY|Y   |
236	         *  +----+----+ - - -
237	         *     \    \
238	         *      \    \
239	         *       +----+
240	         *       |YYYY|  (fixup)
241	         *       +----+
242	         */
243
244		if ((td->td_token & htole32(UHCI_TD_PID)) ==
245		    htole32(UHCI_TD_PID_IN)) {
246			td->fix_pc = ml->fix_pc;
247			usb_pc_cpu_invalidate(ml->fix_pc);
248
249		} else {
250			td->fix_pc = NULL;
251
252			/* copy data to fixup location */
253
254			usbd_copy_out(ml->buf_pc, ml->buf_offset,
255			    ml->fix_res.buffer, td->len);
256
257			usb_pc_cpu_flush(ml->fix_pc);
258		}
259
260		/* prepare next fixup */
261
262		ml->fix_pc++;
263
264	} else {
265
266		td->td_buffer = htole32(ml->buf_res.physaddr);
267		td->fix_pc = NULL;
268	}
269
270	/* prepare next data location */
271
272	ml->buf_offset += td->len;
273}
274
275/*
276 * Return values:
277 * 0: Success
278 * Else: Failure
279 */
280static uint8_t
281uhci_restart(uhci_softc_t *sc)
282{
283	struct usb_page_search buf_res;
284
285	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
286
287  	if (UREAD2(sc, UHCI_CMD) & UHCI_CMD_RS) {
288		DPRINTFN(2, "Already started\n");
289		return (0);
290	}
291
292	DPRINTFN(2, "Restarting\n");
293
294	usbd_get_page(&sc->sc_hw.pframes_pc, 0, &buf_res);
295
296	/* Reload fresh base address */
297	UWRITE4(sc, UHCI_FLBASEADDR, buf_res.physaddr);
298
299	/*
300	 * Assume 64 byte packets at frame end and start HC controller:
301	 */
302	UHCICMD(sc, (UHCI_CMD_MAXP | UHCI_CMD_RS));
303
304	/* wait 10 milliseconds */
305
306	usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 100);
307
308	/* check that controller has started */
309
310	if (UREAD2(sc, UHCI_STS) & UHCI_STS_HCH) {
311		DPRINTFN(2, "Failed\n");
312		return (1);
313	}
314	return (0);
315}
316
317void
318uhci_reset(uhci_softc_t *sc)
319{
320	uint16_t n;
321
322	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
323
324	DPRINTF("resetting the HC\n");
325
326	/* disable interrupts */
327
328	UWRITE2(sc, UHCI_INTR, 0);
329
330	/* global reset */
331
332	UHCICMD(sc, UHCI_CMD_GRESET);
333
334	/* wait */
335
336	usb_pause_mtx(&sc->sc_bus.bus_mtx,
337	    USB_MS_TO_TICKS(USB_BUS_RESET_DELAY));
338
339	/* terminate all transfers */
340
341	UHCICMD(sc, UHCI_CMD_HCRESET);
342
343	/* the reset bit goes low when the controller is done */
344
345	n = UHCI_RESET_TIMEOUT;
346	while (n--) {
347		/* wait one millisecond */
348
349		usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 1000);
350
351		if (!(UREAD2(sc, UHCI_CMD) & UHCI_CMD_HCRESET)) {
352			goto done_1;
353		}
354	}
355
356	device_printf(sc->sc_bus.bdev,
357	    "controller did not reset\n");
358
359done_1:
360
361	n = 10;
362	while (n--) {
363		/* wait one millisecond */
364
365		usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 1000);
366
367		/* check if HC is stopped */
368		if (UREAD2(sc, UHCI_STS) & UHCI_STS_HCH) {
369			goto done_2;
370		}
371	}
372
373	device_printf(sc->sc_bus.bdev,
374	    "controller did not stop\n");
375
376done_2:
377
378	/* reset frame number */
379	UWRITE2(sc, UHCI_FRNUM, 0);
380	/* set default SOF value */
381	UWRITE1(sc, UHCI_SOF, 0x40);
382
383	USB_BUS_UNLOCK(&sc->sc_bus);
384
385	/* stop root interrupt */
386	usb_callout_drain(&sc->sc_root_intr);
387
388	USB_BUS_LOCK(&sc->sc_bus);
389}
390
391static void
392uhci_start(uhci_softc_t *sc)
393{
394	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
395
396	DPRINTFN(2, "enabling\n");
397
398	/* enable interrupts */
399
400	UWRITE2(sc, UHCI_INTR,
401	    (UHCI_INTR_TOCRCIE |
402	    UHCI_INTR_RIE |
403	    UHCI_INTR_IOCE |
404	    UHCI_INTR_SPIE));
405
406	if (uhci_restart(sc)) {
407		device_printf(sc->sc_bus.bdev,
408		    "cannot start HC controller\n");
409	}
410
411	/* start root interrupt */
412	uhci_root_intr(sc);
413}
414
415static struct uhci_qh *
416uhci_init_qh(struct usb_page_cache *pc)
417{
418	struct usb_page_search buf_res;
419	struct uhci_qh *qh;
420
421	usbd_get_page(pc, 0, &buf_res);
422
423	qh = buf_res.buffer;
424
425	qh->qh_self =
426	    htole32(buf_res.physaddr) |
427	    htole32(UHCI_PTR_QH);
428
429	qh->page_cache = pc;
430
431	return (qh);
432}
433
434static struct uhci_td *
435uhci_init_td(struct usb_page_cache *pc)
436{
437	struct usb_page_search buf_res;
438	struct uhci_td *td;
439
440	usbd_get_page(pc, 0, &buf_res);
441
442	td = buf_res.buffer;
443
444	td->td_self =
445	    htole32(buf_res.physaddr) |
446	    htole32(UHCI_PTR_TD);
447
448	td->page_cache = pc;
449
450	return (td);
451}
452
453usb_error_t
454uhci_init(uhci_softc_t *sc)
455{
456	uint16_t bit;
457	uint16_t x;
458	uint16_t y;
459
460	DPRINTF("start\n");
461
462	usb_callout_init_mtx(&sc->sc_root_intr, &sc->sc_bus.bus_mtx, 0);
463
464#ifdef USB_DEBUG
465	if (uhcidebug > 2) {
466		uhci_dumpregs(sc);
467	}
468#endif
469	/*
470	 * Setup QH's
471	 */
472	sc->sc_ls_ctl_p_last =
473	    uhci_init_qh(&sc->sc_hw.ls_ctl_start_pc);
474
475	sc->sc_fs_ctl_p_last =
476	    uhci_init_qh(&sc->sc_hw.fs_ctl_start_pc);
477
478	sc->sc_bulk_p_last =
479	    uhci_init_qh(&sc->sc_hw.bulk_start_pc);
480#if 0
481	sc->sc_reclaim_qh_p =
482	    sc->sc_fs_ctl_p_last;
483#else
484	/* setup reclaim looping point */
485	sc->sc_reclaim_qh_p =
486	    sc->sc_bulk_p_last;
487#endif
488
489	sc->sc_last_qh_p =
490	    uhci_init_qh(&sc->sc_hw.last_qh_pc);
491
492	sc->sc_last_td_p =
493	    uhci_init_td(&sc->sc_hw.last_td_pc);
494
495	for (x = 0; x != UHCI_VFRAMELIST_COUNT; x++) {
496		sc->sc_isoc_p_last[x] =
497		    uhci_init_td(sc->sc_hw.isoc_start_pc + x);
498	}
499
500	for (x = 0; x != UHCI_IFRAMELIST_COUNT; x++) {
501		sc->sc_intr_p_last[x] =
502		    uhci_init_qh(sc->sc_hw.intr_start_pc + x);
503	}
504
505	/*
506	 * the QHs are arranged to give poll intervals that are
507	 * powers of 2 times 1ms
508	 */
509	bit = UHCI_IFRAMELIST_COUNT / 2;
510	while (bit) {
511		x = bit;
512		while (x & bit) {
513			uhci_qh_t *qh_x;
514			uhci_qh_t *qh_y;
515
516			y = (x ^ bit) | (bit / 2);
517
518			/*
519			 * the next QH has half the poll interval
520			 */
521			qh_x = sc->sc_intr_p_last[x];
522			qh_y = sc->sc_intr_p_last[y];
523
524			qh_x->h_next = NULL;
525			qh_x->qh_h_next = qh_y->qh_self;
526			qh_x->e_next = NULL;
527			qh_x->qh_e_next = htole32(UHCI_PTR_T);
528			x++;
529		}
530		bit >>= 1;
531	}
532
533	if (1) {
534		uhci_qh_t *qh_ls;
535		uhci_qh_t *qh_intr;
536
537		qh_ls = sc->sc_ls_ctl_p_last;
538		qh_intr = sc->sc_intr_p_last[0];
539
540		/* start QH for interrupt traffic */
541		qh_intr->h_next = qh_ls;
542		qh_intr->qh_h_next = qh_ls->qh_self;
543		qh_intr->e_next = 0;
544		qh_intr->qh_e_next = htole32(UHCI_PTR_T);
545	}
546	for (x = 0; x != UHCI_VFRAMELIST_COUNT; x++) {
547
548		uhci_td_t *td_x;
549		uhci_qh_t *qh_intr;
550
551		td_x = sc->sc_isoc_p_last[x];
552		qh_intr = sc->sc_intr_p_last[x | (UHCI_IFRAMELIST_COUNT / 2)];
553
554		/* start TD for isochronous traffic */
555		td_x->next = NULL;
556		td_x->td_next = qh_intr->qh_self;
557		td_x->td_status = htole32(UHCI_TD_IOS);
558		td_x->td_token = htole32(0);
559		td_x->td_buffer = htole32(0);
560	}
561
562	if (1) {
563		uhci_qh_t *qh_ls;
564		uhci_qh_t *qh_fs;
565
566		qh_ls = sc->sc_ls_ctl_p_last;
567		qh_fs = sc->sc_fs_ctl_p_last;
568
569		/* start QH where low speed control traffic will be queued */
570		qh_ls->h_next = qh_fs;
571		qh_ls->qh_h_next = qh_fs->qh_self;
572		qh_ls->e_next = 0;
573		qh_ls->qh_e_next = htole32(UHCI_PTR_T);
574	}
575	if (1) {
576		uhci_qh_t *qh_ctl;
577		uhci_qh_t *qh_blk;
578		uhci_qh_t *qh_lst;
579		uhci_td_t *td_lst;
580
581		qh_ctl = sc->sc_fs_ctl_p_last;
582		qh_blk = sc->sc_bulk_p_last;
583
584		/* start QH where full speed control traffic will be queued */
585		qh_ctl->h_next = qh_blk;
586		qh_ctl->qh_h_next = qh_blk->qh_self;
587		qh_ctl->e_next = 0;
588		qh_ctl->qh_e_next = htole32(UHCI_PTR_T);
589
590		qh_lst = sc->sc_last_qh_p;
591
592		/* start QH where bulk traffic will be queued */
593		qh_blk->h_next = qh_lst;
594		qh_blk->qh_h_next = qh_lst->qh_self;
595		qh_blk->e_next = 0;
596		qh_blk->qh_e_next = htole32(UHCI_PTR_T);
597
598		td_lst = sc->sc_last_td_p;
599
600		/* end QH which is used for looping the QHs */
601		qh_lst->h_next = 0;
602		qh_lst->qh_h_next = htole32(UHCI_PTR_T);	/* end of QH chain */
603		qh_lst->e_next = td_lst;
604		qh_lst->qh_e_next = td_lst->td_self;
605
606		/*
607		 * end TD which hangs from the last QH, to avoid a bug in the PIIX
608		 * that makes it run berserk otherwise
609		 */
610		td_lst->next = 0;
611		td_lst->td_next = htole32(UHCI_PTR_T);
612		td_lst->td_status = htole32(0);	/* inactive */
613		td_lst->td_token = htole32(0);
614		td_lst->td_buffer = htole32(0);
615	}
616	if (1) {
617		struct usb_page_search buf_res;
618		uint32_t *pframes;
619
620		usbd_get_page(&sc->sc_hw.pframes_pc, 0, &buf_res);
621
622		pframes = buf_res.buffer;
623
624
625		/*
626		 * Setup UHCI framelist
627		 *
628		 * Execution order:
629		 *
630		 * pframes -> full speed isochronous -> interrupt QH's -> low
631		 * speed control -> full speed control -> bulk transfers
632		 *
633		 */
634
635		for (x = 0; x != UHCI_FRAMELIST_COUNT; x++) {
636			pframes[x] =
637			    sc->sc_isoc_p_last[x % UHCI_VFRAMELIST_COUNT]->td_self;
638		}
639	}
640	/* flush all cache into memory */
641
642	usb_bus_mem_flush_all(&sc->sc_bus, &uhci_iterate_hw_softc);
643
644	/* set up the bus struct */
645	sc->sc_bus.methods = &uhci_bus_methods;
646
647	USB_BUS_LOCK(&sc->sc_bus);
648	/* reset the controller */
649	uhci_reset(sc);
650
651	/* start the controller */
652	uhci_start(sc);
653	USB_BUS_UNLOCK(&sc->sc_bus);
654
655	/* catch lost interrupts */
656	uhci_do_poll(&sc->sc_bus);
657
658	return (0);
659}
660
661static void
662uhci_suspend(uhci_softc_t *sc)
663{
664#ifdef USB_DEBUG
665	if (uhcidebug > 2) {
666		uhci_dumpregs(sc);
667	}
668#endif
669
670	USB_BUS_LOCK(&sc->sc_bus);
671
672	/* stop the controller */
673
674	uhci_reset(sc);
675
676	/* enter global suspend */
677
678	UHCICMD(sc, UHCI_CMD_EGSM);
679
680	USB_BUS_UNLOCK(&sc->sc_bus);
681}
682
683static void
684uhci_resume(uhci_softc_t *sc)
685{
686	USB_BUS_LOCK(&sc->sc_bus);
687
688	/* reset the controller */
689
690	uhci_reset(sc);
691
692	/* force global resume */
693
694	UHCICMD(sc, UHCI_CMD_FGR);
695
696	/* and start traffic again */
697
698	uhci_start(sc);
699
700	USB_BUS_UNLOCK(&sc->sc_bus);
701
702#ifdef USB_DEBUG
703	if (uhcidebug > 2)
704		uhci_dumpregs(sc);
705#endif
706
707	/* catch lost interrupts */
708	uhci_do_poll(&sc->sc_bus);
709}
710
711#ifdef USB_DEBUG
712static void
713uhci_dumpregs(uhci_softc_t *sc)
714{
715	DPRINTFN(0, "%s regs: cmd=%04x, sts=%04x, intr=%04x, frnum=%04x, "
716	    "flbase=%08x, sof=%04x, portsc1=%04x, portsc2=%04x\n",
717	    device_get_nameunit(sc->sc_bus.bdev),
718	    UREAD2(sc, UHCI_CMD),
719	    UREAD2(sc, UHCI_STS),
720	    UREAD2(sc, UHCI_INTR),
721	    UREAD2(sc, UHCI_FRNUM),
722	    UREAD4(sc, UHCI_FLBASEADDR),
723	    UREAD1(sc, UHCI_SOF),
724	    UREAD2(sc, UHCI_PORTSC1),
725	    UREAD2(sc, UHCI_PORTSC2));
726}
727
728static uint8_t
729uhci_dump_td(uhci_td_t *p)
730{
731	uint32_t td_next;
732	uint32_t td_status;
733	uint32_t td_token;
734	uint8_t temp;
735
736	usb_pc_cpu_invalidate(p->page_cache);
737
738	td_next = le32toh(p->td_next);
739	td_status = le32toh(p->td_status);
740	td_token = le32toh(p->td_token);
741
742	/*
743	 * Check whether the link pointer in this TD marks the link pointer
744	 * as end of queue:
745	 */
746	temp = ((td_next & UHCI_PTR_T) || (td_next == 0));
747
748	printf("TD(%p) at 0x%08x = link=0x%08x status=0x%08x "
749	    "token=0x%08x buffer=0x%08x\n",
750	    p,
751	    le32toh(p->td_self),
752	    td_next,
753	    td_status,
754	    td_token,
755	    le32toh(p->td_buffer));
756
757	printf("TD(%p) td_next=%s%s%s td_status=%s%s%s%s%s%s%s%s%s%s%s, errcnt=%d, actlen=%d pid=%02x,"
758	    "addr=%d,endpt=%d,D=%d,maxlen=%d\n",
759	    p,
760	    (td_next & 1) ? "-T" : "",
761	    (td_next & 2) ? "-Q" : "",
762	    (td_next & 4) ? "-VF" : "",
763	    (td_status & UHCI_TD_BITSTUFF) ? "-BITSTUFF" : "",
764	    (td_status & UHCI_TD_CRCTO) ? "-CRCTO" : "",
765	    (td_status & UHCI_TD_NAK) ? "-NAK" : "",
766	    (td_status & UHCI_TD_BABBLE) ? "-BABBLE" : "",
767	    (td_status & UHCI_TD_DBUFFER) ? "-DBUFFER" : "",
768	    (td_status & UHCI_TD_STALLED) ? "-STALLED" : "",
769	    (td_status & UHCI_TD_ACTIVE) ? "-ACTIVE" : "",
770	    (td_status & UHCI_TD_IOC) ? "-IOC" : "",
771	    (td_status & UHCI_TD_IOS) ? "-IOS" : "",
772	    (td_status & UHCI_TD_LS) ? "-LS" : "",
773	    (td_status & UHCI_TD_SPD) ? "-SPD" : "",
774	    UHCI_TD_GET_ERRCNT(td_status),
775	    UHCI_TD_GET_ACTLEN(td_status),
776	    UHCI_TD_GET_PID(td_token),
777	    UHCI_TD_GET_DEVADDR(td_token),
778	    UHCI_TD_GET_ENDPT(td_token),
779	    UHCI_TD_GET_DT(td_token),
780	    UHCI_TD_GET_MAXLEN(td_token));
781
782	return (temp);
783}
784
785static uint8_t
786uhci_dump_qh(uhci_qh_t *sqh)
787{
788	uint8_t temp;
789	uint32_t qh_h_next;
790	uint32_t qh_e_next;
791
792	usb_pc_cpu_invalidate(sqh->page_cache);
793
794	qh_h_next = le32toh(sqh->qh_h_next);
795	qh_e_next = le32toh(sqh->qh_e_next);
796
797	DPRINTFN(0, "QH(%p) at 0x%08x: h_next=0x%08x e_next=0x%08x\n", sqh,
798	    le32toh(sqh->qh_self), qh_h_next, qh_e_next);
799
800	temp = ((((sqh->h_next != NULL) && !(qh_h_next & UHCI_PTR_T)) ? 1 : 0) |
801	    (((sqh->e_next != NULL) && !(qh_e_next & UHCI_PTR_T)) ? 2 : 0));
802
803	return (temp);
804}
805
806static void
807uhci_dump_all(uhci_softc_t *sc)
808{
809	uhci_dumpregs(sc);
810	uhci_dump_qh(sc->sc_ls_ctl_p_last);
811	uhci_dump_qh(sc->sc_fs_ctl_p_last);
812	uhci_dump_qh(sc->sc_bulk_p_last);
813	uhci_dump_qh(sc->sc_last_qh_p);
814}
815
816static void
817uhci_dump_tds(uhci_td_t *td)
818{
819	for (;
820	    td != NULL;
821	    td = td->obj_next) {
822		if (uhci_dump_td(td)) {
823			break;
824		}
825	}
826}
827
828#endif
829
830/*
831 * Let the last QH loop back to the full speed control transfer QH.
832 * This is what intel calls "bandwidth reclamation" and improves
833 * USB performance a lot for some devices.
834 * If we are already looping, just count it.
835 */
836static void
837uhci_add_loop(uhci_softc_t *sc)
838{
839	struct uhci_qh *qh_lst;
840	struct uhci_qh *qh_rec;
841
842#ifdef USB_DEBUG
843	if (uhcinoloop) {
844		return;
845	}
846#endif
847	if (++(sc->sc_loops) == 1) {
848		DPRINTFN(6, "add\n");
849
850		qh_lst = sc->sc_last_qh_p;
851		qh_rec = sc->sc_reclaim_qh_p;
852
853		/* NOTE: we don't loop back the soft pointer */
854
855		qh_lst->qh_h_next = qh_rec->qh_self;
856		usb_pc_cpu_flush(qh_lst->page_cache);
857	}
858}
859
860static void
861uhci_rem_loop(uhci_softc_t *sc)
862{
863	struct uhci_qh *qh_lst;
864
865#ifdef USB_DEBUG
866	if (uhcinoloop) {
867		return;
868	}
869#endif
870	if (--(sc->sc_loops) == 0) {
871		DPRINTFN(6, "remove\n");
872
873		qh_lst = sc->sc_last_qh_p;
874		qh_lst->qh_h_next = htole32(UHCI_PTR_T);
875		usb_pc_cpu_flush(qh_lst->page_cache);
876	}
877}
878
879static void
880uhci_transfer_intr_enqueue(struct usb_xfer *xfer)
881{
882	/* check for early completion */
883	if (uhci_check_transfer(xfer)) {
884		return;
885	}
886	/* put transfer on interrupt queue */
887	usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer);
888
889	/* start timeout, if any */
890	if (xfer->timeout != 0) {
891		usbd_transfer_timeout_ms(xfer, &uhci_timeout, xfer->timeout);
892	}
893}
894
895#define	UHCI_APPEND_TD(std,last) (last) = _uhci_append_td(std,last)
896static uhci_td_t *
897_uhci_append_td(uhci_td_t *std, uhci_td_t *last)
898{
899	DPRINTFN(11, "%p to %p\n", std, last);
900
901	/* (sc->sc_bus.mtx) must be locked */
902
903	std->next = last->next;
904	std->td_next = last->td_next;
905
906	std->prev = last;
907
908	usb_pc_cpu_flush(std->page_cache);
909
910	/*
911	 * the last->next->prev is never followed: std->next->prev = std;
912	 */
913	last->next = std;
914	last->td_next = std->td_self;
915
916	usb_pc_cpu_flush(last->page_cache);
917
918	return (std);
919}
920
921#define	UHCI_APPEND_QH(sqh,last) (last) = _uhci_append_qh(sqh,last)
922static uhci_qh_t *
923_uhci_append_qh(uhci_qh_t *sqh, uhci_qh_t *last)
924{
925	DPRINTFN(11, "%p to %p\n", sqh, last);
926
927	if (sqh->h_prev != NULL) {
928		/* should not happen */
929		DPRINTFN(0, "QH already linked!\n");
930		return (last);
931	}
932	/* (sc->sc_bus.mtx) must be locked */
933
934	sqh->h_next = last->h_next;
935	sqh->qh_h_next = last->qh_h_next;
936
937	sqh->h_prev = last;
938
939	usb_pc_cpu_flush(sqh->page_cache);
940
941	/*
942	 * The "last->h_next->h_prev" is never followed:
943	 *
944	 * "sqh->h_next->h_prev" = sqh;
945	 */
946
947	last->h_next = sqh;
948	last->qh_h_next = sqh->qh_self;
949
950	usb_pc_cpu_flush(last->page_cache);
951
952	return (sqh);
953}
954
955/**/
956
957#define	UHCI_REMOVE_TD(std,last) (last) = _uhci_remove_td(std,last)
958static uhci_td_t *
959_uhci_remove_td(uhci_td_t *std, uhci_td_t *last)
960{
961	DPRINTFN(11, "%p from %p\n", std, last);
962
963	/* (sc->sc_bus.mtx) must be locked */
964
965	std->prev->next = std->next;
966	std->prev->td_next = std->td_next;
967
968	usb_pc_cpu_flush(std->prev->page_cache);
969
970	if (std->next) {
971		std->next->prev = std->prev;
972		usb_pc_cpu_flush(std->next->page_cache);
973	}
974	return ((last == std) ? std->prev : last);
975}
976
977#define	UHCI_REMOVE_QH(sqh,last) (last) = _uhci_remove_qh(sqh,last)
978static uhci_qh_t *
979_uhci_remove_qh(uhci_qh_t *sqh, uhci_qh_t *last)
980{
981	DPRINTFN(11, "%p from %p\n", sqh, last);
982
983	/* (sc->sc_bus.mtx) must be locked */
984
985	/* only remove if not removed from a queue */
986	if (sqh->h_prev) {
987
988		sqh->h_prev->h_next = sqh->h_next;
989		sqh->h_prev->qh_h_next = sqh->qh_h_next;
990
991		usb_pc_cpu_flush(sqh->h_prev->page_cache);
992
993		if (sqh->h_next) {
994			sqh->h_next->h_prev = sqh->h_prev;
995			usb_pc_cpu_flush(sqh->h_next->page_cache);
996		}
997		last = ((last == sqh) ? sqh->h_prev : last);
998
999		sqh->h_prev = 0;
1000
1001		usb_pc_cpu_flush(sqh->page_cache);
1002	}
1003	return (last);
1004}
1005
1006static void
1007uhci_isoc_done(uhci_softc_t *sc, struct usb_xfer *xfer)
1008{
1009	struct usb_page_search res;
1010	uint32_t nframes = xfer->nframes;
1011	uint32_t status;
1012	uint32_t offset = 0;
1013	uint32_t *plen = xfer->frlengths;
1014	uint16_t len = 0;
1015	uhci_td_t *td = xfer->td_transfer_first;
1016	uhci_td_t **pp_last = &sc->sc_isoc_p_last[xfer->qh_pos];
1017
1018	DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n",
1019	    xfer, xfer->endpoint);
1020
1021	/* sync any DMA memory before doing fixups */
1022
1023	usb_bdma_post_sync(xfer);
1024
1025	while (nframes--) {
1026		if (td == NULL) {
1027			panic("%s:%d: out of TD's\n",
1028			    __FUNCTION__, __LINE__);
1029		}
1030		if (pp_last >= &sc->sc_isoc_p_last[UHCI_VFRAMELIST_COUNT]) {
1031			pp_last = &sc->sc_isoc_p_last[0];
1032		}
1033#ifdef USB_DEBUG
1034		if (uhcidebug > 5) {
1035			DPRINTF("isoc TD\n");
1036			uhci_dump_td(td);
1037		}
1038#endif
1039		usb_pc_cpu_invalidate(td->page_cache);
1040		status = le32toh(td->td_status);
1041
1042		len = UHCI_TD_GET_ACTLEN(status);
1043
1044		if (len > *plen) {
1045			len = *plen;
1046		}
1047		if (td->fix_pc) {
1048
1049			usbd_get_page(td->fix_pc, 0, &res);
1050
1051			/* copy data from fixup location to real location */
1052
1053			usb_pc_cpu_invalidate(td->fix_pc);
1054
1055			usbd_copy_in(xfer->frbuffers, offset,
1056			    res.buffer, len);
1057		}
1058		offset += *plen;
1059
1060		*plen = len;
1061
1062		/* remove TD from schedule */
1063		UHCI_REMOVE_TD(td, *pp_last);
1064
1065		pp_last++;
1066		plen++;
1067		td = td->obj_next;
1068	}
1069
1070	xfer->aframes = xfer->nframes;
1071}
1072
1073static usb_error_t
1074uhci_non_isoc_done_sub(struct usb_xfer *xfer)
1075{
1076	struct usb_page_search res;
1077	uhci_td_t *td;
1078	uhci_td_t *td_alt_next;
1079	uint32_t status;
1080	uint32_t token;
1081	uint16_t len;
1082
1083	td = xfer->td_transfer_cache;
1084	td_alt_next = td->alt_next;
1085
1086	if (xfer->aframes != xfer->nframes) {
1087		usbd_xfer_set_frame_len(xfer, xfer->aframes, 0);
1088	}
1089	while (1) {
1090
1091		usb_pc_cpu_invalidate(td->page_cache);
1092		status = le32toh(td->td_status);
1093		token = le32toh(td->td_token);
1094
1095		/*
1096	         * Verify the status and add
1097	         * up the actual length:
1098	         */
1099
1100		len = UHCI_TD_GET_ACTLEN(status);
1101		if (len > td->len) {
1102			/* should not happen */
1103			DPRINTF("Invalid status length, "
1104			    "0x%04x/0x%04x bytes\n", len, td->len);
1105			status |= UHCI_TD_STALLED;
1106
1107		} else if ((xfer->aframes != xfer->nframes) && (len > 0)) {
1108
1109			if (td->fix_pc) {
1110
1111				usbd_get_page(td->fix_pc, 0, &res);
1112
1113				/*
1114				 * copy data from fixup location to real
1115				 * location
1116				 */
1117
1118				usb_pc_cpu_invalidate(td->fix_pc);
1119
1120				usbd_copy_in(xfer->frbuffers + xfer->aframes,
1121				    xfer->frlengths[xfer->aframes], res.buffer, len);
1122			}
1123			/* update actual length */
1124
1125			xfer->frlengths[xfer->aframes] += len;
1126		}
1127		/* Check for last transfer */
1128		if (((void *)td) == xfer->td_transfer_last) {
1129			td = NULL;
1130			break;
1131		}
1132		if (status & UHCI_TD_STALLED) {
1133			/* the transfer is finished */
1134			td = NULL;
1135			break;
1136		}
1137		/* Check for short transfer */
1138		if (len != td->len) {
1139			if (xfer->flags_int.short_frames_ok) {
1140				/* follow alt next */
1141				td = td->alt_next;
1142			} else {
1143				/* the transfer is finished */
1144				td = NULL;
1145			}
1146			break;
1147		}
1148		td = td->obj_next;
1149
1150		if (td->alt_next != td_alt_next) {
1151			/* this USB frame is complete */
1152			break;
1153		}
1154	}
1155
1156	/* update transfer cache */
1157
1158	xfer->td_transfer_cache = td;
1159
1160	/* update data toggle */
1161
1162	xfer->endpoint->toggle_next = (token & UHCI_TD_SET_DT(1)) ? 0 : 1;
1163
1164#ifdef USB_DEBUG
1165	if (status & UHCI_TD_ERROR) {
1166		DPRINTFN(11, "error, addr=%d, endpt=0x%02x, frame=0x%02x "
1167		    "status=%s%s%s%s%s%s%s%s%s%s%s\n",
1168		    xfer->address, xfer->endpointno, xfer->aframes,
1169		    (status & UHCI_TD_BITSTUFF) ? "[BITSTUFF]" : "",
1170		    (status & UHCI_TD_CRCTO) ? "[CRCTO]" : "",
1171		    (status & UHCI_TD_NAK) ? "[NAK]" : "",
1172		    (status & UHCI_TD_BABBLE) ? "[BABBLE]" : "",
1173		    (status & UHCI_TD_DBUFFER) ? "[DBUFFER]" : "",
1174		    (status & UHCI_TD_STALLED) ? "[STALLED]" : "",
1175		    (status & UHCI_TD_ACTIVE) ? "[ACTIVE]" : "[NOT_ACTIVE]",
1176		    (status & UHCI_TD_IOC) ? "[IOC]" : "",
1177		    (status & UHCI_TD_IOS) ? "[IOS]" : "",
1178		    (status & UHCI_TD_LS) ? "[LS]" : "",
1179		    (status & UHCI_TD_SPD) ? "[SPD]" : "");
1180	}
1181#endif
1182	return (status & UHCI_TD_STALLED) ?
1183	    USB_ERR_STALLED : USB_ERR_NORMAL_COMPLETION;
1184}
1185
1186static void
1187uhci_non_isoc_done(struct usb_xfer *xfer)
1188{
1189	usb_error_t err = 0;
1190
1191	DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n",
1192	    xfer, xfer->endpoint);
1193
1194#ifdef USB_DEBUG
1195	if (uhcidebug > 10) {
1196		uhci_dump_tds(xfer->td_transfer_first);
1197	}
1198#endif
1199
1200	/* sync any DMA memory before doing fixups */
1201
1202	usb_bdma_post_sync(xfer);
1203
1204	/* reset scanner */
1205
1206	xfer->td_transfer_cache = xfer->td_transfer_first;
1207
1208	if (xfer->flags_int.control_xfr) {
1209		if (xfer->flags_int.control_hdr) {
1210
1211			err = uhci_non_isoc_done_sub(xfer);
1212		}
1213		xfer->aframes = 1;
1214
1215		if (xfer->td_transfer_cache == NULL) {
1216			goto done;
1217		}
1218	}
1219	while (xfer->aframes != xfer->nframes) {
1220
1221		err = uhci_non_isoc_done_sub(xfer);
1222		xfer->aframes++;
1223
1224		if (xfer->td_transfer_cache == NULL) {
1225			goto done;
1226		}
1227	}
1228
1229	if (xfer->flags_int.control_xfr &&
1230	    !xfer->flags_int.control_act) {
1231
1232		err = uhci_non_isoc_done_sub(xfer);
1233	}
1234done:
1235	uhci_device_done(xfer, err);
1236}
1237
1238/*------------------------------------------------------------------------*
1239 *	uhci_check_transfer_sub
1240 *
1241 * The main purpose of this function is to update the data-toggle
1242 * in case it is wrong.
1243 *------------------------------------------------------------------------*/
1244static void
1245uhci_check_transfer_sub(struct usb_xfer *xfer)
1246{
1247	uhci_qh_t *qh;
1248	uhci_td_t *td;
1249	uhci_td_t *td_alt_next;
1250
1251	uint32_t td_token;
1252	uint32_t td_self;
1253
1254	td = xfer->td_transfer_cache;
1255	qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1256
1257	td_token = td->obj_next->td_token;
1258	td = td->alt_next;
1259	xfer->td_transfer_cache = td;
1260	td_self = td->td_self;
1261	td_alt_next = td->alt_next;
1262
1263	if (xfer->flags_int.control_xfr)
1264		goto skip;	/* don't touch the DT value! */
1265
1266	if (!((td->td_token ^ td_token) & htole32(UHCI_TD_SET_DT(1))))
1267		goto skip;	/* data toggle has correct value */
1268
1269	/*
1270	 * The data toggle is wrong and we need to toggle it !
1271	 */
1272	while (1) {
1273
1274		td->td_token ^= htole32(UHCI_TD_SET_DT(1));
1275		usb_pc_cpu_flush(td->page_cache);
1276
1277		if (td == xfer->td_transfer_last) {
1278			/* last transfer */
1279			break;
1280		}
1281		td = td->obj_next;
1282
1283		if (td->alt_next != td_alt_next) {
1284			/* next frame */
1285			break;
1286		}
1287	}
1288skip:
1289
1290	/* update the QH */
1291	qh->qh_e_next = td_self;
1292	usb_pc_cpu_flush(qh->page_cache);
1293
1294	DPRINTFN(13, "xfer=%p following alt next\n", xfer);
1295}
1296
1297/*------------------------------------------------------------------------*
1298 *	uhci_check_transfer
1299 *
1300 * Return values:
1301 *    0: USB transfer is not finished
1302 * Else: USB transfer is finished
1303 *------------------------------------------------------------------------*/
1304static uint8_t
1305uhci_check_transfer(struct usb_xfer *xfer)
1306{
1307	uint32_t status;
1308	uint32_t token;
1309	uhci_td_t *td;
1310
1311	DPRINTFN(16, "xfer=%p checking transfer\n", xfer);
1312
1313	if (xfer->endpoint->methods == &uhci_device_isoc_methods) {
1314		/* isochronous transfer */
1315
1316		td = xfer->td_transfer_last;
1317
1318		usb_pc_cpu_invalidate(td->page_cache);
1319		status = le32toh(td->td_status);
1320
1321		/* check also if the first is complete */
1322
1323		td = xfer->td_transfer_first;
1324
1325		usb_pc_cpu_invalidate(td->page_cache);
1326		status |= le32toh(td->td_status);
1327
1328		if (!(status & UHCI_TD_ACTIVE)) {
1329			uhci_device_done(xfer, USB_ERR_NORMAL_COMPLETION);
1330			goto transferred;
1331		}
1332	} else {
1333		/* non-isochronous transfer */
1334
1335		/*
1336		 * check whether there is an error somewhere
1337		 * in the middle, or whether there was a short
1338		 * packet (SPD and not ACTIVE)
1339		 */
1340		td = xfer->td_transfer_cache;
1341
1342		while (1) {
1343			usb_pc_cpu_invalidate(td->page_cache);
1344			status = le32toh(td->td_status);
1345			token = le32toh(td->td_token);
1346
1347			/*
1348			 * if there is an active TD the transfer isn't done
1349			 */
1350			if (status & UHCI_TD_ACTIVE) {
1351				/* update cache */
1352				xfer->td_transfer_cache = td;
1353				goto done;
1354			}
1355			/*
1356			 * last transfer descriptor makes the transfer done
1357			 */
1358			if (((void *)td) == xfer->td_transfer_last) {
1359				break;
1360			}
1361			/*
1362			 * any kind of error makes the transfer done
1363			 */
1364			if (status & UHCI_TD_STALLED) {
1365				break;
1366			}
1367			/*
1368			 * check if we reached the last packet
1369			 * or if there is a short packet:
1370			 */
1371			if ((td->td_next == htole32(UHCI_PTR_T)) ||
1372			    (UHCI_TD_GET_ACTLEN(status) < td->len)) {
1373
1374				if (xfer->flags_int.short_frames_ok) {
1375					/* follow alt next */
1376					if (td->alt_next) {
1377						/* update cache */
1378						xfer->td_transfer_cache = td;
1379						uhci_check_transfer_sub(xfer);
1380						goto done;
1381					}
1382				}
1383				/* transfer is done */
1384				break;
1385			}
1386			td = td->obj_next;
1387		}
1388		uhci_non_isoc_done(xfer);
1389		goto transferred;
1390	}
1391
1392done:
1393	DPRINTFN(13, "xfer=%p is still active\n", xfer);
1394	return (0);
1395
1396transferred:
1397	return (1);
1398}
1399
1400static void
1401uhci_interrupt_poll(uhci_softc_t *sc)
1402{
1403	struct usb_xfer *xfer;
1404
1405repeat:
1406	TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
1407		/*
1408		 * check if transfer is transferred
1409		 */
1410		if (uhci_check_transfer(xfer)) {
1411			/* queue has been modified */
1412			goto repeat;
1413		}
1414	}
1415}
1416
1417/*------------------------------------------------------------------------*
1418 *	uhci_interrupt - UHCI interrupt handler
1419 *
1420 * NOTE: Do not access "sc->sc_bus.bdev" inside the interrupt handler,
1421 * hence the interrupt handler will be setup before "sc->sc_bus.bdev"
1422 * is present !
1423 *------------------------------------------------------------------------*/
1424void
1425uhci_interrupt(uhci_softc_t *sc)
1426{
1427	uint32_t status;
1428
1429	USB_BUS_LOCK(&sc->sc_bus);
1430
1431	DPRINTFN(16, "real interrupt\n");
1432
1433#ifdef USB_DEBUG
1434	if (uhcidebug > 15) {
1435		uhci_dumpregs(sc);
1436	}
1437#endif
1438	status = UREAD2(sc, UHCI_STS) & UHCI_STS_ALLINTRS;
1439	if (status == 0) {
1440		/* the interrupt was not for us */
1441		goto done;
1442	}
1443	if (status & (UHCI_STS_RD | UHCI_STS_HSE |
1444	    UHCI_STS_HCPE | UHCI_STS_HCH)) {
1445
1446		if (status & UHCI_STS_RD) {
1447#ifdef USB_DEBUG
1448			printf("%s: resume detect\n",
1449			    __FUNCTION__);
1450#endif
1451		}
1452		if (status & UHCI_STS_HSE) {
1453			printf("%s: host system error\n",
1454			    __FUNCTION__);
1455		}
1456		if (status & UHCI_STS_HCPE) {
1457			printf("%s: host controller process error\n",
1458			    __FUNCTION__);
1459		}
1460		if (status & UHCI_STS_HCH) {
1461			/* no acknowledge needed */
1462			DPRINTF("%s: host controller halted\n",
1463			    __FUNCTION__);
1464#ifdef USB_DEBUG
1465			if (uhcidebug > 0) {
1466				uhci_dump_all(sc);
1467			}
1468#endif
1469		}
1470	}
1471	/* get acknowledge bits */
1472	status &= (UHCI_STS_USBINT |
1473	    UHCI_STS_USBEI |
1474	    UHCI_STS_RD |
1475	    UHCI_STS_HSE |
1476	    UHCI_STS_HCPE);
1477
1478	if (status == 0) {
1479		/* nothing to acknowledge */
1480		goto done;
1481	}
1482	/* acknowledge interrupts */
1483	UWRITE2(sc, UHCI_STS, status);
1484
1485	/* poll all the USB transfers */
1486	uhci_interrupt_poll(sc);
1487
1488done:
1489	USB_BUS_UNLOCK(&sc->sc_bus);
1490}
1491
1492/*
1493 * called when a request does not complete
1494 */
1495static void
1496uhci_timeout(void *arg)
1497{
1498	struct usb_xfer *xfer = arg;
1499
1500	DPRINTF("xfer=%p\n", xfer);
1501
1502	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1503
1504	/* transfer is transferred */
1505	uhci_device_done(xfer, USB_ERR_TIMEOUT);
1506}
1507
1508static void
1509uhci_do_poll(struct usb_bus *bus)
1510{
1511	struct uhci_softc *sc = UHCI_BUS2SC(bus);
1512
1513	USB_BUS_LOCK(&sc->sc_bus);
1514	uhci_interrupt_poll(sc);
1515	USB_BUS_UNLOCK(&sc->sc_bus);
1516}
1517
1518static void
1519uhci_setup_standard_chain_sub(struct uhci_std_temp *temp)
1520{
1521	uhci_td_t *td;
1522	uhci_td_t *td_next;
1523	uhci_td_t *td_alt_next;
1524	uint32_t average;
1525	uint32_t len_old;
1526	uint8_t shortpkt_old;
1527	uint8_t precompute;
1528
1529	td_alt_next = NULL;
1530	shortpkt_old = temp->shortpkt;
1531	len_old = temp->len;
1532	precompute = 1;
1533
1534	/* software is used to detect short incoming transfers */
1535
1536	if ((temp->td_token & htole32(UHCI_TD_PID)) == htole32(UHCI_TD_PID_IN)) {
1537		temp->td_status |= htole32(UHCI_TD_SPD);
1538	} else {
1539		temp->td_status &= ~htole32(UHCI_TD_SPD);
1540	}
1541
1542	temp->ml.buf_offset = 0;
1543
1544restart:
1545
1546	temp->td_token &= ~htole32(UHCI_TD_SET_MAXLEN(0));
1547	temp->td_token |= htole32(UHCI_TD_SET_MAXLEN(temp->average));
1548
1549	td = temp->td;
1550	td_next = temp->td_next;
1551
1552	while (1) {
1553
1554		if (temp->len == 0) {
1555
1556			if (temp->shortpkt) {
1557				break;
1558			}
1559			/* send a Zero Length Packet, ZLP, last */
1560
1561			temp->shortpkt = 1;
1562			temp->td_token |= htole32(UHCI_TD_SET_MAXLEN(0));
1563			average = 0;
1564
1565		} else {
1566
1567			average = temp->average;
1568
1569			if (temp->len < average) {
1570				temp->shortpkt = 1;
1571				temp->td_token &= ~htole32(UHCI_TD_SET_MAXLEN(0));
1572				temp->td_token |= htole32(UHCI_TD_SET_MAXLEN(temp->len));
1573				average = temp->len;
1574			}
1575		}
1576
1577		if (td_next == NULL) {
1578			panic("%s: out of UHCI transfer descriptors!", __FUNCTION__);
1579		}
1580		/* get next TD */
1581
1582		td = td_next;
1583		td_next = td->obj_next;
1584
1585		/* check if we are pre-computing */
1586
1587		if (precompute) {
1588
1589			/* update remaining length */
1590
1591			temp->len -= average;
1592
1593			continue;
1594		}
1595		/* fill out current TD */
1596
1597		td->td_status = temp->td_status;
1598		td->td_token = temp->td_token;
1599
1600		/* update data toggle */
1601
1602		temp->td_token ^= htole32(UHCI_TD_SET_DT(1));
1603
1604		if (average == 0) {
1605
1606			td->len = 0;
1607			td->td_buffer = 0;
1608			td->fix_pc = NULL;
1609
1610		} else {
1611
1612			/* update remaining length */
1613
1614			temp->len -= average;
1615
1616			td->len = average;
1617
1618			/* fill out buffer pointer and do fixup, if any */
1619
1620			uhci_mem_layout_fixup(&temp->ml, td);
1621		}
1622
1623		td->alt_next = td_alt_next;
1624
1625		if ((td_next == td_alt_next) && temp->setup_alt_next) {
1626			/* we need to receive these frames one by one ! */
1627			td->td_status |= htole32(UHCI_TD_IOC);
1628			td->td_next = htole32(UHCI_PTR_T);
1629		} else {
1630			if (td_next) {
1631				/* link the current TD with the next one */
1632				td->td_next = td_next->td_self;
1633			}
1634		}
1635
1636		usb_pc_cpu_flush(td->page_cache);
1637	}
1638
1639	if (precompute) {
1640		precompute = 0;
1641
1642		/* setup alt next pointer, if any */
1643		if (temp->last_frame) {
1644			td_alt_next = NULL;
1645		} else {
1646			/* we use this field internally */
1647			td_alt_next = td_next;
1648		}
1649
1650		/* restore */
1651		temp->shortpkt = shortpkt_old;
1652		temp->len = len_old;
1653		goto restart;
1654	}
1655	temp->td = td;
1656	temp->td_next = td_next;
1657}
1658
1659static uhci_td_t *
1660uhci_setup_standard_chain(struct usb_xfer *xfer)
1661{
1662	struct uhci_std_temp temp;
1663	uhci_td_t *td;
1664	uint32_t x;
1665
1666	DPRINTFN(9, "addr=%d endpt=%d sumlen=%d speed=%d\n",
1667	    xfer->address, UE_GET_ADDR(xfer->endpointno),
1668	    xfer->sumlen, usbd_get_speed(xfer->xroot->udev));
1669
1670	temp.average = xfer->max_frame_size;
1671	temp.max_frame_size = xfer->max_frame_size;
1672
1673	/* toggle the DMA set we are using */
1674	xfer->flags_int.curr_dma_set ^= 1;
1675
1676	/* get next DMA set */
1677	td = xfer->td_start[xfer->flags_int.curr_dma_set];
1678	xfer->td_transfer_first = td;
1679	xfer->td_transfer_cache = td;
1680
1681	temp.td = NULL;
1682	temp.td_next = td;
1683	temp.last_frame = 0;
1684	temp.setup_alt_next = xfer->flags_int.short_frames_ok;
1685
1686	uhci_mem_layout_init(&temp.ml, xfer);
1687
1688	temp.td_status =
1689	    htole32(UHCI_TD_ZERO_ACTLEN(UHCI_TD_SET_ERRCNT(3) |
1690	    UHCI_TD_ACTIVE));
1691
1692	if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
1693		temp.td_status |= htole32(UHCI_TD_LS);
1694	}
1695	temp.td_token =
1696	    htole32(UHCI_TD_SET_ENDPT(xfer->endpointno) |
1697	    UHCI_TD_SET_DEVADDR(xfer->address));
1698
1699	if (xfer->endpoint->toggle_next) {
1700		/* DATA1 is next */
1701		temp.td_token |= htole32(UHCI_TD_SET_DT(1));
1702	}
1703	/* check if we should prepend a setup message */
1704
1705	if (xfer->flags_int.control_xfr) {
1706
1707		if (xfer->flags_int.control_hdr) {
1708
1709			temp.td_token &= htole32(UHCI_TD_SET_DEVADDR(0x7F) |
1710			    UHCI_TD_SET_ENDPT(0xF));
1711			temp.td_token |= htole32(UHCI_TD_PID_SETUP |
1712			    UHCI_TD_SET_DT(0));
1713
1714			temp.len = xfer->frlengths[0];
1715			temp.ml.buf_pc = xfer->frbuffers + 0;
1716			temp.shortpkt = temp.len ? 1 : 0;
1717			/* check for last frame */
1718			if (xfer->nframes == 1) {
1719				/* no STATUS stage yet, SETUP is last */
1720				if (xfer->flags_int.control_act) {
1721					temp.last_frame = 1;
1722					temp.setup_alt_next = 0;
1723				}
1724			}
1725			uhci_setup_standard_chain_sub(&temp);
1726		}
1727		x = 1;
1728	} else {
1729		x = 0;
1730	}
1731
1732	while (x != xfer->nframes) {
1733
1734		/* DATA0 / DATA1 message */
1735
1736		temp.len = xfer->frlengths[x];
1737		temp.ml.buf_pc = xfer->frbuffers + x;
1738
1739		x++;
1740
1741		if (x == xfer->nframes) {
1742			if (xfer->flags_int.control_xfr) {
1743				/* no STATUS stage yet, DATA is last */
1744				if (xfer->flags_int.control_act) {
1745					temp.last_frame = 1;
1746					temp.setup_alt_next = 0;
1747				}
1748			} else {
1749				temp.last_frame = 1;
1750				temp.setup_alt_next = 0;
1751			}
1752		}
1753		/*
1754		 * Keep previous data toggle,
1755		 * device address and endpoint number:
1756		 */
1757
1758		temp.td_token &= htole32(UHCI_TD_SET_DEVADDR(0x7F) |
1759		    UHCI_TD_SET_ENDPT(0xF) |
1760		    UHCI_TD_SET_DT(1));
1761
1762		if (temp.len == 0) {
1763
1764			/* make sure that we send an USB packet */
1765
1766			temp.shortpkt = 0;
1767
1768		} else {
1769
1770			/* regular data transfer */
1771
1772			temp.shortpkt = (xfer->flags.force_short_xfer) ? 0 : 1;
1773		}
1774
1775		/* set endpoint direction */
1776
1777		temp.td_token |=
1778		    (UE_GET_DIR(xfer->endpointno) == UE_DIR_IN) ?
1779		    htole32(UHCI_TD_PID_IN) :
1780		    htole32(UHCI_TD_PID_OUT);
1781
1782		uhci_setup_standard_chain_sub(&temp);
1783	}
1784
1785	/* check if we should append a status stage */
1786
1787	if (xfer->flags_int.control_xfr &&
1788	    !xfer->flags_int.control_act) {
1789
1790		/*
1791		 * send a DATA1 message and reverse the current endpoint
1792		 * direction
1793		 */
1794
1795		temp.td_token &= htole32(UHCI_TD_SET_DEVADDR(0x7F) |
1796		    UHCI_TD_SET_ENDPT(0xF) |
1797		    UHCI_TD_SET_DT(1));
1798		temp.td_token |=
1799		    (UE_GET_DIR(xfer->endpointno) == UE_DIR_OUT) ?
1800		    htole32(UHCI_TD_PID_IN | UHCI_TD_SET_DT(1)) :
1801		    htole32(UHCI_TD_PID_OUT | UHCI_TD_SET_DT(1));
1802
1803		temp.len = 0;
1804		temp.ml.buf_pc = NULL;
1805		temp.shortpkt = 0;
1806		temp.last_frame = 1;
1807		temp.setup_alt_next = 0;
1808
1809		uhci_setup_standard_chain_sub(&temp);
1810	}
1811	td = temp.td;
1812
1813	/* Ensure that last TD is terminating: */
1814	td->td_next = htole32(UHCI_PTR_T);
1815
1816	/* set interrupt bit */
1817
1818	td->td_status |= htole32(UHCI_TD_IOC);
1819
1820	usb_pc_cpu_flush(td->page_cache);
1821
1822	/* must have at least one frame! */
1823
1824	xfer->td_transfer_last = td;
1825
1826#ifdef USB_DEBUG
1827	if (uhcidebug > 8) {
1828		DPRINTF("nexttog=%d; data before transfer:\n",
1829		    xfer->endpoint->toggle_next);
1830		uhci_dump_tds(xfer->td_transfer_first);
1831	}
1832#endif
1833	return (xfer->td_transfer_first);
1834}
1835
1836/* NOTE: "done" can be run two times in a row,
1837 * from close and from interrupt
1838 */
1839
1840static void
1841uhci_device_done(struct usb_xfer *xfer, usb_error_t error)
1842{
1843	struct usb_pipe_methods *methods = xfer->endpoint->methods;
1844	uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
1845	uhci_qh_t *qh;
1846
1847	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
1848
1849	DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n",
1850	    xfer, xfer->endpoint, error);
1851
1852	qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1853	if (qh) {
1854		usb_pc_cpu_invalidate(qh->page_cache);
1855	}
1856	if (xfer->flags_int.bandwidth_reclaimed) {
1857		xfer->flags_int.bandwidth_reclaimed = 0;
1858		uhci_rem_loop(sc);
1859	}
1860	if (methods == &uhci_device_bulk_methods) {
1861		UHCI_REMOVE_QH(qh, sc->sc_bulk_p_last);
1862	}
1863	if (methods == &uhci_device_ctrl_methods) {
1864		if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
1865			UHCI_REMOVE_QH(qh, sc->sc_ls_ctl_p_last);
1866		} else {
1867			UHCI_REMOVE_QH(qh, sc->sc_fs_ctl_p_last);
1868		}
1869	}
1870	if (methods == &uhci_device_intr_methods) {
1871		UHCI_REMOVE_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
1872	}
1873	/*
1874	 * Only finish isochronous transfers once
1875	 * which will update "xfer->frlengths".
1876	 */
1877	if (xfer->td_transfer_first &&
1878	    xfer->td_transfer_last) {
1879		if (methods == &uhci_device_isoc_methods) {
1880			uhci_isoc_done(sc, xfer);
1881		}
1882		xfer->td_transfer_first = NULL;
1883		xfer->td_transfer_last = NULL;
1884	}
1885	/* dequeue transfer and start next transfer */
1886	usbd_transfer_done(xfer, error);
1887}
1888
1889/*------------------------------------------------------------------------*
1890 * uhci bulk support
1891 *------------------------------------------------------------------------*/
1892static void
1893uhci_device_bulk_open(struct usb_xfer *xfer)
1894{
1895	return;
1896}
1897
1898static void
1899uhci_device_bulk_close(struct usb_xfer *xfer)
1900{
1901	uhci_device_done(xfer, USB_ERR_CANCELLED);
1902}
1903
1904static void
1905uhci_device_bulk_enter(struct usb_xfer *xfer)
1906{
1907	return;
1908}
1909
1910static void
1911uhci_device_bulk_start(struct usb_xfer *xfer)
1912{
1913	uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
1914	uhci_td_t *td;
1915	uhci_qh_t *qh;
1916
1917	/* setup TD's */
1918	td = uhci_setup_standard_chain(xfer);
1919
1920	/* setup QH */
1921	qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1922
1923	qh->e_next = td;
1924	qh->qh_e_next = td->td_self;
1925
1926	if (xfer->xroot->udev->flags.self_suspended == 0) {
1927		UHCI_APPEND_QH(qh, sc->sc_bulk_p_last);
1928		uhci_add_loop(sc);
1929		xfer->flags_int.bandwidth_reclaimed = 1;
1930	} else {
1931		usb_pc_cpu_flush(qh->page_cache);
1932	}
1933
1934	/* put transfer on interrupt queue */
1935	uhci_transfer_intr_enqueue(xfer);
1936}
1937
1938struct usb_pipe_methods uhci_device_bulk_methods =
1939{
1940	.open = uhci_device_bulk_open,
1941	.close = uhci_device_bulk_close,
1942	.enter = uhci_device_bulk_enter,
1943	.start = uhci_device_bulk_start,
1944};
1945
1946/*------------------------------------------------------------------------*
1947 * uhci control support
1948 *------------------------------------------------------------------------*/
1949static void
1950uhci_device_ctrl_open(struct usb_xfer *xfer)
1951{
1952	return;
1953}
1954
1955static void
1956uhci_device_ctrl_close(struct usb_xfer *xfer)
1957{
1958	uhci_device_done(xfer, USB_ERR_CANCELLED);
1959}
1960
1961static void
1962uhci_device_ctrl_enter(struct usb_xfer *xfer)
1963{
1964	return;
1965}
1966
1967static void
1968uhci_device_ctrl_start(struct usb_xfer *xfer)
1969{
1970	uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
1971	uhci_qh_t *qh;
1972	uhci_td_t *td;
1973
1974	/* setup TD's */
1975	td = uhci_setup_standard_chain(xfer);
1976
1977	/* setup QH */
1978	qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1979
1980	qh->e_next = td;
1981	qh->qh_e_next = td->td_self;
1982
1983	/*
1984	 * NOTE: some devices choke on bandwidth- reclamation for control
1985	 * transfers
1986	 */
1987	if (xfer->xroot->udev->flags.self_suspended == 0) {
1988		if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
1989			UHCI_APPEND_QH(qh, sc->sc_ls_ctl_p_last);
1990		} else {
1991			UHCI_APPEND_QH(qh, sc->sc_fs_ctl_p_last);
1992		}
1993	} else {
1994		usb_pc_cpu_flush(qh->page_cache);
1995	}
1996	/* put transfer on interrupt queue */
1997	uhci_transfer_intr_enqueue(xfer);
1998}
1999
2000struct usb_pipe_methods uhci_device_ctrl_methods =
2001{
2002	.open = uhci_device_ctrl_open,
2003	.close = uhci_device_ctrl_close,
2004	.enter = uhci_device_ctrl_enter,
2005	.start = uhci_device_ctrl_start,
2006};
2007
2008/*------------------------------------------------------------------------*
2009 * uhci interrupt support
2010 *------------------------------------------------------------------------*/
2011static void
2012uhci_device_intr_open(struct usb_xfer *xfer)
2013{
2014	uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
2015	uint16_t best;
2016	uint16_t bit;
2017	uint16_t x;
2018
2019	best = 0;
2020	bit = UHCI_IFRAMELIST_COUNT / 2;
2021	while (bit) {
2022		if (xfer->interval >= bit) {
2023			x = bit;
2024			best = bit;
2025			while (x & bit) {
2026				if (sc->sc_intr_stat[x] <
2027				    sc->sc_intr_stat[best]) {
2028					best = x;
2029				}
2030				x++;
2031			}
2032			break;
2033		}
2034		bit >>= 1;
2035	}
2036
2037	sc->sc_intr_stat[best]++;
2038	xfer->qh_pos = best;
2039
2040	DPRINTFN(3, "best=%d interval=%d\n",
2041	    best, xfer->interval);
2042}
2043
2044static void
2045uhci_device_intr_close(struct usb_xfer *xfer)
2046{
2047	uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
2048
2049	sc->sc_intr_stat[xfer->qh_pos]--;
2050
2051	uhci_device_done(xfer, USB_ERR_CANCELLED);
2052}
2053
2054static void
2055uhci_device_intr_enter(struct usb_xfer *xfer)
2056{
2057	return;
2058}
2059
2060static void
2061uhci_device_intr_start(struct usb_xfer *xfer)
2062{
2063	uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
2064	uhci_qh_t *qh;
2065	uhci_td_t *td;
2066
2067	/* setup TD's */
2068	td = uhci_setup_standard_chain(xfer);
2069
2070	/* setup QH */
2071	qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
2072
2073	qh->e_next = td;
2074	qh->qh_e_next = td->td_self;
2075
2076	if (xfer->xroot->udev->flags.self_suspended == 0) {
2077		/* enter QHs into the controller data structures */
2078		UHCI_APPEND_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
2079	} else {
2080		usb_pc_cpu_flush(qh->page_cache);
2081	}
2082
2083	/* put transfer on interrupt queue */
2084	uhci_transfer_intr_enqueue(xfer);
2085}
2086
2087struct usb_pipe_methods uhci_device_intr_methods =
2088{
2089	.open = uhci_device_intr_open,
2090	.close = uhci_device_intr_close,
2091	.enter = uhci_device_intr_enter,
2092	.start = uhci_device_intr_start,
2093};
2094
2095/*------------------------------------------------------------------------*
2096 * uhci isochronous support
2097 *------------------------------------------------------------------------*/
2098static void
2099uhci_device_isoc_open(struct usb_xfer *xfer)
2100{
2101	uhci_td_t *td;
2102	uint32_t td_token;
2103	uint8_t ds;
2104
2105	td_token =
2106	    (UE_GET_DIR(xfer->endpointno) == UE_DIR_IN) ?
2107	    UHCI_TD_IN(0, xfer->endpointno, xfer->address, 0) :
2108	    UHCI_TD_OUT(0, xfer->endpointno, xfer->address, 0);
2109
2110	td_token = htole32(td_token);
2111
2112	/* initialize all TD's */
2113
2114	for (ds = 0; ds != 2; ds++) {
2115
2116		for (td = xfer->td_start[ds]; td; td = td->obj_next) {
2117
2118			/* mark TD as inactive */
2119			td->td_status = htole32(UHCI_TD_IOS);
2120			td->td_token = td_token;
2121
2122			usb_pc_cpu_flush(td->page_cache);
2123		}
2124	}
2125}
2126
2127static void
2128uhci_device_isoc_close(struct usb_xfer *xfer)
2129{
2130	uhci_device_done(xfer, USB_ERR_CANCELLED);
2131}
2132
2133static void
2134uhci_device_isoc_enter(struct usb_xfer *xfer)
2135{
2136	struct uhci_mem_layout ml;
2137	uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
2138	uint32_t nframes;
2139	uint32_t temp;
2140	uint32_t *plen;
2141
2142#ifdef USB_DEBUG
2143	uint8_t once = 1;
2144
2145#endif
2146	uhci_td_t *td;
2147	uhci_td_t *td_last = NULL;
2148	uhci_td_t **pp_last;
2149
2150	DPRINTFN(6, "xfer=%p next=%d nframes=%d\n",
2151	    xfer, xfer->endpoint->isoc_next, xfer->nframes);
2152
2153	nframes = UREAD2(sc, UHCI_FRNUM);
2154
2155	temp = (nframes - xfer->endpoint->isoc_next) &
2156	    (UHCI_VFRAMELIST_COUNT - 1);
2157
2158	if ((xfer->endpoint->is_synced == 0) ||
2159	    (temp < xfer->nframes)) {
2160		/*
2161		 * If there is data underflow or the pipe queue is empty we
2162		 * schedule the transfer a few frames ahead of the current
2163		 * frame position. Else two isochronous transfers might
2164		 * overlap.
2165		 */
2166		xfer->endpoint->isoc_next = (nframes + 3) & (UHCI_VFRAMELIST_COUNT - 1);
2167		xfer->endpoint->is_synced = 1;
2168		DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next);
2169	}
2170	/*
2171	 * compute how many milliseconds the insertion is ahead of the
2172	 * current frame position:
2173	 */
2174	temp = (xfer->endpoint->isoc_next - nframes) &
2175	    (UHCI_VFRAMELIST_COUNT - 1);
2176
2177	/*
2178	 * pre-compute when the isochronous transfer will be finished:
2179	 */
2180	xfer->isoc_time_complete =
2181	    usb_isoc_time_expand(&sc->sc_bus, nframes) + temp +
2182	    xfer->nframes;
2183
2184	/* get the real number of frames */
2185
2186	nframes = xfer->nframes;
2187
2188	uhci_mem_layout_init(&ml, xfer);
2189
2190	plen = xfer->frlengths;
2191
2192	/* toggle the DMA set we are using */
2193	xfer->flags_int.curr_dma_set ^= 1;
2194
2195	/* get next DMA set */
2196	td = xfer->td_start[xfer->flags_int.curr_dma_set];
2197	xfer->td_transfer_first = td;
2198
2199	pp_last = &sc->sc_isoc_p_last[xfer->endpoint->isoc_next];
2200
2201	/* store starting position */
2202
2203	xfer->qh_pos = xfer->endpoint->isoc_next;
2204
2205	while (nframes--) {
2206		if (td == NULL) {
2207			panic("%s:%d: out of TD's\n",
2208			    __FUNCTION__, __LINE__);
2209		}
2210		if (pp_last >= &sc->sc_isoc_p_last[UHCI_VFRAMELIST_COUNT]) {
2211			pp_last = &sc->sc_isoc_p_last[0];
2212		}
2213		if (*plen > xfer->max_frame_size) {
2214#ifdef USB_DEBUG
2215			if (once) {
2216				once = 0;
2217				printf("%s: frame length(%d) exceeds %d "
2218				    "bytes (frame truncated)\n",
2219				    __FUNCTION__, *plen,
2220				    xfer->max_frame_size);
2221			}
2222#endif
2223			*plen = xfer->max_frame_size;
2224		}
2225		/* reuse td_token from last transfer */
2226
2227		td->td_token &= htole32(~UHCI_TD_MAXLEN_MASK);
2228		td->td_token |= htole32(UHCI_TD_SET_MAXLEN(*plen));
2229
2230		td->len = *plen;
2231
2232		if (td->len == 0) {
2233			/*
2234			 * Do not call "uhci_mem_layout_fixup()" when the
2235			 * length is zero!
2236			 */
2237			td->td_buffer = 0;
2238			td->fix_pc = NULL;
2239
2240		} else {
2241
2242			/* fill out buffer pointer and do fixup, if any */
2243
2244			uhci_mem_layout_fixup(&ml, td);
2245
2246		}
2247
2248		/* update status */
2249		if (nframes == 0) {
2250			td->td_status = htole32
2251			    (UHCI_TD_ZERO_ACTLEN
2252			    (UHCI_TD_SET_ERRCNT(0) |
2253			    UHCI_TD_ACTIVE |
2254			    UHCI_TD_IOS |
2255			    UHCI_TD_IOC));
2256		} else {
2257			td->td_status = htole32
2258			    (UHCI_TD_ZERO_ACTLEN
2259			    (UHCI_TD_SET_ERRCNT(0) |
2260			    UHCI_TD_ACTIVE |
2261			    UHCI_TD_IOS));
2262		}
2263
2264		usb_pc_cpu_flush(td->page_cache);
2265
2266#ifdef USB_DEBUG
2267		if (uhcidebug > 5) {
2268			DPRINTF("TD %d\n", nframes);
2269			uhci_dump_td(td);
2270		}
2271#endif
2272		/* insert TD into schedule */
2273		UHCI_APPEND_TD(td, *pp_last);
2274		pp_last++;
2275
2276		plen++;
2277		td_last = td;
2278		td = td->obj_next;
2279	}
2280
2281	xfer->td_transfer_last = td_last;
2282
2283	/* update isoc_next */
2284	xfer->endpoint->isoc_next = (pp_last - &sc->sc_isoc_p_last[0]) &
2285	    (UHCI_VFRAMELIST_COUNT - 1);
2286}
2287
2288static void
2289uhci_device_isoc_start(struct usb_xfer *xfer)
2290{
2291	/* put transfer on interrupt queue */
2292	uhci_transfer_intr_enqueue(xfer);
2293}
2294
2295struct usb_pipe_methods uhci_device_isoc_methods =
2296{
2297	.open = uhci_device_isoc_open,
2298	.close = uhci_device_isoc_close,
2299	.enter = uhci_device_isoc_enter,
2300	.start = uhci_device_isoc_start,
2301};
2302
2303/*------------------------------------------------------------------------*
2304 * uhci root control support
2305 *------------------------------------------------------------------------*
2306 * Simulate a hardware hub by handling all the necessary requests.
2307 *------------------------------------------------------------------------*/
2308
2309static const
2310struct usb_device_descriptor uhci_devd =
2311{
2312	sizeof(struct usb_device_descriptor),
2313	UDESC_DEVICE,			/* type */
2314	{0x00, 0x01},			/* USB version */
2315	UDCLASS_HUB,			/* class */
2316	UDSUBCLASS_HUB,			/* subclass */
2317	UDPROTO_FSHUB,			/* protocol */
2318	64,				/* max packet */
2319	{0}, {0}, {0x00, 0x01},		/* device id */
2320	1, 2, 0,			/* string indicies */
2321	1				/* # of configurations */
2322};
2323
2324static const struct uhci_config_desc uhci_confd = {
2325	.confd = {
2326		.bLength = sizeof(struct usb_config_descriptor),
2327		.bDescriptorType = UDESC_CONFIG,
2328		.wTotalLength[0] = sizeof(uhci_confd),
2329		.bNumInterface = 1,
2330		.bConfigurationValue = 1,
2331		.iConfiguration = 0,
2332		.bmAttributes = UC_SELF_POWERED,
2333		.bMaxPower = 0		/* max power */
2334	},
2335	.ifcd = {
2336		.bLength = sizeof(struct usb_interface_descriptor),
2337		.bDescriptorType = UDESC_INTERFACE,
2338		.bNumEndpoints = 1,
2339		.bInterfaceClass = UICLASS_HUB,
2340		.bInterfaceSubClass = UISUBCLASS_HUB,
2341		.bInterfaceProtocol = UIPROTO_FSHUB,
2342	},
2343	.endpd = {
2344		.bLength = sizeof(struct usb_endpoint_descriptor),
2345		.bDescriptorType = UDESC_ENDPOINT,
2346		.bEndpointAddress = UE_DIR_IN | UHCI_INTR_ENDPT,
2347		.bmAttributes = UE_INTERRUPT,
2348		.wMaxPacketSize[0] = 8,	/* max packet (63 ports) */
2349		.bInterval = 255,
2350	},
2351};
2352
2353static const
2354struct usb_hub_descriptor_min uhci_hubd_piix =
2355{
2356	.bDescLength = sizeof(uhci_hubd_piix),
2357	.bDescriptorType = UDESC_HUB,
2358	.bNbrPorts = 2,
2359	.wHubCharacteristics = {UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL, 0},
2360	.bPwrOn2PwrGood = 50,
2361};
2362
2363/*
2364 * The USB hub protocol requires that SET_FEATURE(PORT_RESET) also
2365 * enables the port, and also states that SET_FEATURE(PORT_ENABLE)
2366 * should not be used by the USB subsystem.  As we cannot issue a
2367 * SET_FEATURE(PORT_ENABLE) externally, we must ensure that the port
2368 * will be enabled as part of the reset.
2369 *
2370 * On the VT83C572, the port cannot be successfully enabled until the
2371 * outstanding "port enable change" and "connection status change"
2372 * events have been reset.
2373 */
2374static usb_error_t
2375uhci_portreset(uhci_softc_t *sc, uint16_t index)
2376{
2377	uint16_t port;
2378	uint16_t x;
2379	uint8_t lim;
2380
2381	if (index == 1)
2382		port = UHCI_PORTSC1;
2383	else if (index == 2)
2384		port = UHCI_PORTSC2;
2385	else
2386		return (USB_ERR_IOERROR);
2387
2388	/*
2389	 * Before we do anything, turn on SOF messages on the USB
2390	 * BUS. Some USB devices do not cope without them!
2391	 */
2392	uhci_restart(sc);
2393
2394	x = URWMASK(UREAD2(sc, port));
2395	UWRITE2(sc, port, x | UHCI_PORTSC_PR);
2396
2397	usb_pause_mtx(&sc->sc_bus.bus_mtx,
2398	    USB_MS_TO_TICKS(usb_port_root_reset_delay));
2399
2400	DPRINTFN(4, "uhci port %d reset, status0 = 0x%04x\n",
2401	    index, UREAD2(sc, port));
2402
2403	x = URWMASK(UREAD2(sc, port));
2404	UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
2405
2406
2407	mtx_unlock(&sc->sc_bus.bus_mtx);
2408
2409	/*
2410	 * This delay needs to be exactly 100us, else some USB devices
2411	 * fail to attach!
2412	 */
2413	DELAY(100);
2414
2415	mtx_lock(&sc->sc_bus.bus_mtx);
2416
2417	DPRINTFN(4, "uhci port %d reset, status1 = 0x%04x\n",
2418	    index, UREAD2(sc, port));
2419
2420	x = URWMASK(UREAD2(sc, port));
2421	UWRITE2(sc, port, x | UHCI_PORTSC_PE);
2422
2423	for (lim = 0; lim < 12; lim++) {
2424
2425		usb_pause_mtx(&sc->sc_bus.bus_mtx,
2426		    USB_MS_TO_TICKS(usb_port_reset_delay));
2427
2428		x = UREAD2(sc, port);
2429
2430		DPRINTFN(4, "uhci port %d iteration %u, status = 0x%04x\n",
2431		    index, lim, x);
2432
2433		if (!(x & UHCI_PORTSC_CCS)) {
2434			/*
2435			 * No device is connected (or was disconnected
2436			 * during reset).  Consider the port reset.
2437			 * The delay must be long enough to ensure on
2438			 * the initial iteration that the device
2439			 * connection will have been registered.  50ms
2440			 * appears to be sufficient, but 20ms is not.
2441			 */
2442			DPRINTFN(4, "uhci port %d loop %u, device detached\n",
2443			    index, lim);
2444			goto done;
2445		}
2446		if (x & (UHCI_PORTSC_POEDC | UHCI_PORTSC_CSC)) {
2447			/*
2448			 * Port enabled changed and/or connection
2449			 * status changed were set.  Reset either or
2450			 * both raised flags (by writing a 1 to that
2451			 * bit), and wait again for state to settle.
2452			 */
2453			UWRITE2(sc, port, URWMASK(x) |
2454			    (x & (UHCI_PORTSC_POEDC | UHCI_PORTSC_CSC)));
2455			continue;
2456		}
2457		if (x & UHCI_PORTSC_PE) {
2458			/* port is enabled */
2459			goto done;
2460		}
2461		UWRITE2(sc, port, URWMASK(x) | UHCI_PORTSC_PE);
2462	}
2463
2464	DPRINTFN(2, "uhci port %d reset timed out\n", index);
2465	return (USB_ERR_TIMEOUT);
2466
2467done:
2468	DPRINTFN(4, "uhci port %d reset, status2 = 0x%04x\n",
2469	    index, UREAD2(sc, port));
2470
2471	sc->sc_isreset = 1;
2472	return (USB_ERR_NORMAL_COMPLETION);
2473}
2474
2475static usb_error_t
2476uhci_roothub_exec(struct usb_device *udev,
2477    struct usb_device_request *req, const void **pptr, uint16_t *plength)
2478{
2479	uhci_softc_t *sc = UHCI_BUS2SC(udev->bus);
2480	const void *ptr;
2481	const char *str_ptr;
2482	uint16_t x;
2483	uint16_t port;
2484	uint16_t value;
2485	uint16_t index;
2486	uint16_t status;
2487	uint16_t change;
2488	uint16_t len;
2489	usb_error_t err;
2490
2491	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
2492
2493	/* buffer reset */
2494	ptr = (const void *)&sc->sc_hub_desc.temp;
2495	len = 0;
2496	err = 0;
2497
2498	value = UGETW(req->wValue);
2499	index = UGETW(req->wIndex);
2500
2501	DPRINTFN(3, "type=0x%02x request=0x%02x wLen=0x%04x "
2502	    "wValue=0x%04x wIndex=0x%04x\n",
2503	    req->bmRequestType, req->bRequest,
2504	    UGETW(req->wLength), value, index);
2505
2506#define	C(x,y) ((x) | ((y) << 8))
2507	switch (C(req->bRequest, req->bmRequestType)) {
2508	case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
2509	case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
2510	case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
2511		/*
2512		 * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
2513		 * for the integrated root hub.
2514		 */
2515		break;
2516	case C(UR_GET_CONFIG, UT_READ_DEVICE):
2517		len = 1;
2518		sc->sc_hub_desc.temp[0] = sc->sc_conf;
2519		break;
2520	case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
2521		switch (value >> 8) {
2522		case UDESC_DEVICE:
2523			if ((value & 0xff) != 0) {
2524				err = USB_ERR_IOERROR;
2525				goto done;
2526			}
2527			len = sizeof(uhci_devd);
2528			ptr = (const void *)&uhci_devd;
2529			break;
2530
2531		case UDESC_CONFIG:
2532			if ((value & 0xff) != 0) {
2533				err = USB_ERR_IOERROR;
2534				goto done;
2535			}
2536			len = sizeof(uhci_confd);
2537			ptr = (const void *)&uhci_confd;
2538			break;
2539
2540		case UDESC_STRING:
2541			switch (value & 0xff) {
2542			case 0:	/* Language table */
2543				str_ptr = "\001";
2544				break;
2545
2546			case 1:	/* Vendor */
2547				str_ptr = sc->sc_vendor;
2548				break;
2549
2550			case 2:	/* Product */
2551				str_ptr = "UHCI root HUB";
2552				break;
2553
2554			default:
2555				str_ptr = "";
2556				break;
2557			}
2558
2559			len = usb_make_str_desc
2560			    (sc->sc_hub_desc.temp,
2561			    sizeof(sc->sc_hub_desc.temp),
2562			    str_ptr);
2563			break;
2564
2565		default:
2566			err = USB_ERR_IOERROR;
2567			goto done;
2568		}
2569		break;
2570	case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
2571		len = 1;
2572		sc->sc_hub_desc.temp[0] = 0;
2573		break;
2574	case C(UR_GET_STATUS, UT_READ_DEVICE):
2575		len = 2;
2576		USETW(sc->sc_hub_desc.stat.wStatus, UDS_SELF_POWERED);
2577		break;
2578	case C(UR_GET_STATUS, UT_READ_INTERFACE):
2579	case C(UR_GET_STATUS, UT_READ_ENDPOINT):
2580		len = 2;
2581		USETW(sc->sc_hub_desc.stat.wStatus, 0);
2582		break;
2583	case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
2584		if (value >= UHCI_MAX_DEVICES) {
2585			err = USB_ERR_IOERROR;
2586			goto done;
2587		}
2588		sc->sc_addr = value;
2589		break;
2590	case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
2591		if ((value != 0) && (value != 1)) {
2592			err = USB_ERR_IOERROR;
2593			goto done;
2594		}
2595		sc->sc_conf = value;
2596		break;
2597	case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
2598		break;
2599	case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
2600	case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
2601	case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
2602		err = USB_ERR_IOERROR;
2603		goto done;
2604	case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
2605		break;
2606	case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
2607		break;
2608		/* Hub requests */
2609	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
2610		break;
2611	case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
2612		DPRINTFN(4, "UR_CLEAR_PORT_FEATURE "
2613		    "port=%d feature=%d\n",
2614		    index, value);
2615		if (index == 1)
2616			port = UHCI_PORTSC1;
2617		else if (index == 2)
2618			port = UHCI_PORTSC2;
2619		else {
2620			err = USB_ERR_IOERROR;
2621			goto done;
2622		}
2623		switch (value) {
2624		case UHF_PORT_ENABLE:
2625			x = URWMASK(UREAD2(sc, port));
2626			UWRITE2(sc, port, x & ~UHCI_PORTSC_PE);
2627			break;
2628		case UHF_PORT_SUSPEND:
2629			x = URWMASK(UREAD2(sc, port));
2630			UWRITE2(sc, port, x & ~(UHCI_PORTSC_SUSP));
2631			break;
2632		case UHF_PORT_RESET:
2633			x = URWMASK(UREAD2(sc, port));
2634			UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
2635			break;
2636		case UHF_C_PORT_CONNECTION:
2637			x = URWMASK(UREAD2(sc, port));
2638			UWRITE2(sc, port, x | UHCI_PORTSC_CSC);
2639			break;
2640		case UHF_C_PORT_ENABLE:
2641			x = URWMASK(UREAD2(sc, port));
2642			UWRITE2(sc, port, x | UHCI_PORTSC_POEDC);
2643			break;
2644		case UHF_C_PORT_OVER_CURRENT:
2645			x = URWMASK(UREAD2(sc, port));
2646			UWRITE2(sc, port, x | UHCI_PORTSC_OCIC);
2647			break;
2648		case UHF_C_PORT_RESET:
2649			sc->sc_isreset = 0;
2650			err = USB_ERR_NORMAL_COMPLETION;
2651			goto done;
2652		case UHF_C_PORT_SUSPEND:
2653			sc->sc_isresumed &= ~(1 << index);
2654			break;
2655		case UHF_PORT_CONNECTION:
2656		case UHF_PORT_OVER_CURRENT:
2657		case UHF_PORT_POWER:
2658		case UHF_PORT_LOW_SPEED:
2659		default:
2660			err = USB_ERR_IOERROR;
2661			goto done;
2662		}
2663		break;
2664	case C(UR_GET_BUS_STATE, UT_READ_CLASS_OTHER):
2665		if (index == 1)
2666			port = UHCI_PORTSC1;
2667		else if (index == 2)
2668			port = UHCI_PORTSC2;
2669		else {
2670			err = USB_ERR_IOERROR;
2671			goto done;
2672		}
2673		len = 1;
2674		sc->sc_hub_desc.temp[0] =
2675		    ((UREAD2(sc, port) & UHCI_PORTSC_LS) >>
2676		    UHCI_PORTSC_LS_SHIFT);
2677		break;
2678	case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
2679		if ((value & 0xff) != 0) {
2680			err = USB_ERR_IOERROR;
2681			goto done;
2682		}
2683		len = sizeof(uhci_hubd_piix);
2684		ptr = (const void *)&uhci_hubd_piix;
2685		break;
2686	case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
2687		len = 16;
2688		memset(sc->sc_hub_desc.temp, 0, 16);
2689		break;
2690	case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
2691		if (index == 1)
2692			port = UHCI_PORTSC1;
2693		else if (index == 2)
2694			port = UHCI_PORTSC2;
2695		else {
2696			err = USB_ERR_IOERROR;
2697			goto done;
2698		}
2699		x = UREAD2(sc, port);
2700		status = change = 0;
2701		if (x & UHCI_PORTSC_CCS)
2702			status |= UPS_CURRENT_CONNECT_STATUS;
2703		if (x & UHCI_PORTSC_CSC)
2704			change |= UPS_C_CONNECT_STATUS;
2705		if (x & UHCI_PORTSC_PE)
2706			status |= UPS_PORT_ENABLED;
2707		if (x & UHCI_PORTSC_POEDC)
2708			change |= UPS_C_PORT_ENABLED;
2709		if (x & UHCI_PORTSC_OCI)
2710			status |= UPS_OVERCURRENT_INDICATOR;
2711		if (x & UHCI_PORTSC_OCIC)
2712			change |= UPS_C_OVERCURRENT_INDICATOR;
2713		if (x & UHCI_PORTSC_LSDA)
2714			status |= UPS_LOW_SPEED;
2715		if ((x & UHCI_PORTSC_PE) && (x & UHCI_PORTSC_RD)) {
2716			/* need to do a write back */
2717			UWRITE2(sc, port, URWMASK(x));
2718
2719			/* wait 20ms for resume sequence to complete */
2720			usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50);
2721
2722			/* clear suspend and resume detect */
2723			UWRITE2(sc, port, URWMASK(x) & ~(UHCI_PORTSC_RD |
2724			    UHCI_PORTSC_SUSP));
2725
2726			/* wait a little bit */
2727			usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 500);
2728
2729			sc->sc_isresumed |= (1 << index);
2730
2731		} else if (x & UHCI_PORTSC_SUSP) {
2732			status |= UPS_SUSPEND;
2733		}
2734		status |= UPS_PORT_POWER;
2735		if (sc->sc_isresumed & (1 << index))
2736			change |= UPS_C_SUSPEND;
2737		if (sc->sc_isreset)
2738			change |= UPS_C_PORT_RESET;
2739		USETW(sc->sc_hub_desc.ps.wPortStatus, status);
2740		USETW(sc->sc_hub_desc.ps.wPortChange, change);
2741		len = sizeof(sc->sc_hub_desc.ps);
2742		break;
2743	case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
2744		err = USB_ERR_IOERROR;
2745		goto done;
2746	case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
2747		break;
2748	case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
2749		if (index == 1)
2750			port = UHCI_PORTSC1;
2751		else if (index == 2)
2752			port = UHCI_PORTSC2;
2753		else {
2754			err = USB_ERR_IOERROR;
2755			goto done;
2756		}
2757		switch (value) {
2758		case UHF_PORT_ENABLE:
2759			x = URWMASK(UREAD2(sc, port));
2760			UWRITE2(sc, port, x | UHCI_PORTSC_PE);
2761			break;
2762		case UHF_PORT_SUSPEND:
2763			x = URWMASK(UREAD2(sc, port));
2764			UWRITE2(sc, port, x | UHCI_PORTSC_SUSP);
2765			break;
2766		case UHF_PORT_RESET:
2767			err = uhci_portreset(sc, index);
2768			goto done;
2769		case UHF_PORT_POWER:
2770			/* pretend we turned on power */
2771			err = USB_ERR_NORMAL_COMPLETION;
2772			goto done;
2773		case UHF_C_PORT_CONNECTION:
2774		case UHF_C_PORT_ENABLE:
2775		case UHF_C_PORT_OVER_CURRENT:
2776		case UHF_PORT_CONNECTION:
2777		case UHF_PORT_OVER_CURRENT:
2778		case UHF_PORT_LOW_SPEED:
2779		case UHF_C_PORT_SUSPEND:
2780		case UHF_C_PORT_RESET:
2781		default:
2782			err = USB_ERR_IOERROR;
2783			goto done;
2784		}
2785		break;
2786	default:
2787		err = USB_ERR_IOERROR;
2788		goto done;
2789	}
2790done:
2791	*plength = len;
2792	*pptr = ptr;
2793	return (err);
2794}
2795
2796/*
2797 * This routine is executed periodically and simulates interrupts from
2798 * the root controller interrupt pipe for port status change:
2799 */
2800static void
2801uhci_root_intr(uhci_softc_t *sc)
2802{
2803	DPRINTFN(21, "\n");
2804
2805	USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
2806
2807	sc->sc_hub_idata[0] = 0;
2808
2809	if (UREAD2(sc, UHCI_PORTSC1) & (UHCI_PORTSC_CSC |
2810	    UHCI_PORTSC_OCIC | UHCI_PORTSC_RD)) {
2811		sc->sc_hub_idata[0] |= 1 << 1;
2812	}
2813	if (UREAD2(sc, UHCI_PORTSC2) & (UHCI_PORTSC_CSC |
2814	    UHCI_PORTSC_OCIC | UHCI_PORTSC_RD)) {
2815		sc->sc_hub_idata[0] |= 1 << 2;
2816	}
2817
2818	/* restart timer */
2819	usb_callout_reset(&sc->sc_root_intr, hz,
2820	    (void *)&uhci_root_intr, sc);
2821
2822	if (sc->sc_hub_idata[0] != 0) {
2823		uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata,
2824		    sizeof(sc->sc_hub_idata));
2825	}
2826}
2827
2828static void
2829uhci_xfer_setup(struct usb_setup_params *parm)
2830{
2831	struct usb_page_search page_info;
2832	struct usb_page_cache *pc;
2833	uhci_softc_t *sc;
2834	struct usb_xfer *xfer;
2835	void *last_obj;
2836	uint32_t ntd;
2837	uint32_t nqh;
2838	uint32_t nfixup;
2839	uint32_t n;
2840	uint16_t align;
2841
2842	sc = UHCI_BUS2SC(parm->udev->bus);
2843	xfer = parm->curr_xfer;
2844
2845	parm->hc_max_packet_size = 0x500;
2846	parm->hc_max_packet_count = 1;
2847	parm->hc_max_frame_size = 0x500;
2848
2849	/*
2850	 * compute ntd and nqh
2851	 */
2852	if (parm->methods == &uhci_device_ctrl_methods) {
2853		xfer->flags_int.bdma_enable = 1;
2854		xfer->flags_int.bdma_no_post_sync = 1;
2855
2856		usbd_transfer_setup_sub(parm);
2857
2858		/* see EHCI HC driver for proof of "ntd" formula */
2859
2860		nqh = 1;
2861		ntd = ((2 * xfer->nframes) + 1	/* STATUS */
2862		    + (xfer->max_data_length / xfer->max_frame_size));
2863
2864	} else if (parm->methods == &uhci_device_bulk_methods) {
2865		xfer->flags_int.bdma_enable = 1;
2866		xfer->flags_int.bdma_no_post_sync = 1;
2867
2868		usbd_transfer_setup_sub(parm);
2869
2870		nqh = 1;
2871		ntd = ((2 * xfer->nframes)
2872		    + (xfer->max_data_length / xfer->max_frame_size));
2873
2874	} else if (parm->methods == &uhci_device_intr_methods) {
2875		xfer->flags_int.bdma_enable = 1;
2876		xfer->flags_int.bdma_no_post_sync = 1;
2877
2878		usbd_transfer_setup_sub(parm);
2879
2880		nqh = 1;
2881		ntd = ((2 * xfer->nframes)
2882		    + (xfer->max_data_length / xfer->max_frame_size));
2883
2884	} else if (parm->methods == &uhci_device_isoc_methods) {
2885		xfer->flags_int.bdma_enable = 1;
2886		xfer->flags_int.bdma_no_post_sync = 1;
2887
2888		usbd_transfer_setup_sub(parm);
2889
2890		nqh = 0;
2891		ntd = xfer->nframes;
2892
2893	} else {
2894
2895		usbd_transfer_setup_sub(parm);
2896
2897		nqh = 0;
2898		ntd = 0;
2899	}
2900
2901	if (parm->err) {
2902		return;
2903	}
2904	/*
2905	 * NOTE: the UHCI controller requires that
2906	 * every packet must be contiguous on
2907	 * the same USB memory page !
2908	 */
2909	nfixup = (parm->bufsize / USB_PAGE_SIZE) + 1;
2910
2911	/*
2912	 * Compute a suitable power of two alignment
2913	 * for our "max_frame_size" fixup buffer(s):
2914	 */
2915	align = xfer->max_frame_size;
2916	n = 0;
2917	while (align) {
2918		align >>= 1;
2919		n++;
2920	}
2921
2922	/* check for power of two */
2923	if (!(xfer->max_frame_size &
2924	    (xfer->max_frame_size - 1))) {
2925		n--;
2926	}
2927	/*
2928	 * We don't allow alignments of
2929	 * less than 8 bytes:
2930	 *
2931	 * NOTE: Allocating using an aligment
2932	 * of 1 byte has special meaning!
2933	 */
2934	if (n < 3) {
2935		n = 3;
2936	}
2937	align = (1 << n);
2938
2939	if (usbd_transfer_setup_sub_malloc(
2940	    parm, &pc, xfer->max_frame_size,
2941	    align, nfixup)) {
2942		parm->err = USB_ERR_NOMEM;
2943		return;
2944	}
2945	xfer->buf_fixup = pc;
2946
2947alloc_dma_set:
2948
2949	if (parm->err) {
2950		return;
2951	}
2952	last_obj = NULL;
2953
2954	if (usbd_transfer_setup_sub_malloc(
2955	    parm, &pc, sizeof(uhci_td_t),
2956	    UHCI_TD_ALIGN, ntd)) {
2957		parm->err = USB_ERR_NOMEM;
2958		return;
2959	}
2960	if (parm->buf) {
2961		for (n = 0; n != ntd; n++) {
2962			uhci_td_t *td;
2963
2964			usbd_get_page(pc + n, 0, &page_info);
2965
2966			td = page_info.buffer;
2967
2968			/* init TD */
2969			if ((parm->methods == &uhci_device_bulk_methods) ||
2970			    (parm->methods == &uhci_device_ctrl_methods) ||
2971			    (parm->methods == &uhci_device_intr_methods)) {
2972				/* set depth first bit */
2973				td->td_self = htole32(page_info.physaddr |
2974				    UHCI_PTR_TD | UHCI_PTR_VF);
2975			} else {
2976				td->td_self = htole32(page_info.physaddr |
2977				    UHCI_PTR_TD);
2978			}
2979
2980			td->obj_next = last_obj;
2981			td->page_cache = pc + n;
2982
2983			last_obj = td;
2984
2985			usb_pc_cpu_flush(pc + n);
2986		}
2987	}
2988	xfer->td_start[xfer->flags_int.curr_dma_set] = last_obj;
2989
2990	last_obj = NULL;
2991
2992	if (usbd_transfer_setup_sub_malloc(
2993	    parm, &pc, sizeof(uhci_qh_t),
2994	    UHCI_QH_ALIGN, nqh)) {
2995		parm->err = USB_ERR_NOMEM;
2996		return;
2997	}
2998	if (parm->buf) {
2999		for (n = 0; n != nqh; n++) {
3000			uhci_qh_t *qh;
3001
3002			usbd_get_page(pc + n, 0, &page_info);
3003
3004			qh = page_info.buffer;
3005
3006			/* init QH */
3007			qh->qh_self = htole32(page_info.physaddr | UHCI_PTR_QH);
3008			qh->obj_next = last_obj;
3009			qh->page_cache = pc + n;
3010
3011			last_obj = qh;
3012
3013			usb_pc_cpu_flush(pc + n);
3014		}
3015	}
3016	xfer->qh_start[xfer->flags_int.curr_dma_set] = last_obj;
3017
3018	if (!xfer->flags_int.curr_dma_set) {
3019		xfer->flags_int.curr_dma_set = 1;
3020		goto alloc_dma_set;
3021	}
3022}
3023
3024static void
3025uhci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc,
3026    struct usb_endpoint *ep)
3027{
3028	uhci_softc_t *sc = UHCI_BUS2SC(udev->bus);
3029
3030	DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d (%d)\n",
3031	    ep, udev->address,
3032	    edesc->bEndpointAddress, udev->flags.usb_mode,
3033	    sc->sc_addr);
3034
3035	if (udev->device_index != sc->sc_addr) {
3036		switch (edesc->bmAttributes & UE_XFERTYPE) {
3037		case UE_CONTROL:
3038			ep->methods = &uhci_device_ctrl_methods;
3039			break;
3040		case UE_INTERRUPT:
3041			ep->methods = &uhci_device_intr_methods;
3042			break;
3043		case UE_ISOCHRONOUS:
3044			if (udev->speed == USB_SPEED_FULL) {
3045				ep->methods = &uhci_device_isoc_methods;
3046			}
3047			break;
3048		case UE_BULK:
3049			ep->methods = &uhci_device_bulk_methods;
3050			break;
3051		default:
3052			/* do nothing */
3053			break;
3054		}
3055	}
3056}
3057
3058static void
3059uhci_xfer_unsetup(struct usb_xfer *xfer)
3060{
3061	return;
3062}
3063
3064static void
3065uhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
3066{
3067	/*
3068	 * Wait until hardware has finished any possible use of the
3069	 * transfer descriptor(s) and QH
3070	 */
3071	*pus = (1125);			/* microseconds */
3072}
3073
3074static void
3075uhci_device_resume(struct usb_device *udev)
3076{
3077	struct uhci_softc *sc = UHCI_BUS2SC(udev->bus);
3078	struct usb_xfer *xfer;
3079	struct usb_pipe_methods *methods;
3080	uhci_qh_t *qh;
3081
3082	DPRINTF("\n");
3083
3084	USB_BUS_LOCK(udev->bus);
3085
3086	TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3087
3088		if (xfer->xroot->udev == udev) {
3089
3090			methods = xfer->endpoint->methods;
3091			qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
3092
3093			if (methods == &uhci_device_bulk_methods) {
3094				UHCI_APPEND_QH(qh, sc->sc_bulk_p_last);
3095				uhci_add_loop(sc);
3096				xfer->flags_int.bandwidth_reclaimed = 1;
3097			}
3098			if (methods == &uhci_device_ctrl_methods) {
3099				if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
3100					UHCI_APPEND_QH(qh, sc->sc_ls_ctl_p_last);
3101				} else {
3102					UHCI_APPEND_QH(qh, sc->sc_fs_ctl_p_last);
3103				}
3104			}
3105			if (methods == &uhci_device_intr_methods) {
3106				UHCI_APPEND_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
3107			}
3108		}
3109	}
3110
3111	USB_BUS_UNLOCK(udev->bus);
3112
3113	return;
3114}
3115
3116static void
3117uhci_device_suspend(struct usb_device *udev)
3118{
3119	struct uhci_softc *sc = UHCI_BUS2SC(udev->bus);
3120	struct usb_xfer *xfer;
3121	struct usb_pipe_methods *methods;
3122	uhci_qh_t *qh;
3123
3124	DPRINTF("\n");
3125
3126	USB_BUS_LOCK(udev->bus);
3127
3128	TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3129
3130		if (xfer->xroot->udev == udev) {
3131
3132			methods = xfer->endpoint->methods;
3133			qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
3134
3135			if (xfer->flags_int.bandwidth_reclaimed) {
3136				xfer->flags_int.bandwidth_reclaimed = 0;
3137				uhci_rem_loop(sc);
3138			}
3139			if (methods == &uhci_device_bulk_methods) {
3140				UHCI_REMOVE_QH(qh, sc->sc_bulk_p_last);
3141			}
3142			if (methods == &uhci_device_ctrl_methods) {
3143				if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
3144					UHCI_REMOVE_QH(qh, sc->sc_ls_ctl_p_last);
3145				} else {
3146					UHCI_REMOVE_QH(qh, sc->sc_fs_ctl_p_last);
3147				}
3148			}
3149			if (methods == &uhci_device_intr_methods) {
3150				UHCI_REMOVE_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
3151			}
3152		}
3153	}
3154
3155	USB_BUS_UNLOCK(udev->bus);
3156
3157	return;
3158}
3159
3160static void
3161uhci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state)
3162{
3163	struct uhci_softc *sc = UHCI_BUS2SC(bus);
3164
3165	switch (state) {
3166	case USB_HW_POWER_SUSPEND:
3167	case USB_HW_POWER_SHUTDOWN:
3168		uhci_suspend(sc);
3169		break;
3170	case USB_HW_POWER_RESUME:
3171		uhci_resume(sc);
3172		break;
3173	default:
3174		break;
3175	}
3176}
3177
3178static void
3179uhci_set_hw_power(struct usb_bus *bus)
3180{
3181	struct uhci_softc *sc = UHCI_BUS2SC(bus);
3182	uint32_t flags;
3183
3184	DPRINTF("\n");
3185
3186	USB_BUS_LOCK(bus);
3187
3188	flags = bus->hw_power_state;
3189
3190	/*
3191	 * WARNING: Some FULL speed USB devices require periodic SOF
3192	 * messages! If any USB devices are connected through the
3193	 * UHCI, power save will be disabled!
3194	 */
3195	if (flags & (USB_HW_POWER_CONTROL |
3196	    USB_HW_POWER_NON_ROOT_HUB |
3197	    USB_HW_POWER_BULK |
3198	    USB_HW_POWER_INTERRUPT |
3199	    USB_HW_POWER_ISOC)) {
3200		DPRINTF("Some USB transfer is "
3201		    "active on unit %u.\n",
3202		    device_get_unit(sc->sc_bus.bdev));
3203		uhci_restart(sc);
3204	} else {
3205		DPRINTF("Power save on unit %u.\n",
3206		    device_get_unit(sc->sc_bus.bdev));
3207		UHCICMD(sc, UHCI_CMD_MAXP);
3208	}
3209
3210	USB_BUS_UNLOCK(bus);
3211
3212	return;
3213}
3214
3215
3216struct usb_bus_methods uhci_bus_methods =
3217{
3218	.endpoint_init = uhci_ep_init,
3219	.xfer_setup = uhci_xfer_setup,
3220	.xfer_unsetup = uhci_xfer_unsetup,
3221	.get_dma_delay = uhci_get_dma_delay,
3222	.device_resume = uhci_device_resume,
3223	.device_suspend = uhci_device_suspend,
3224	.set_hw_power = uhci_set_hw_power,
3225	.set_hw_power_sleep = uhci_set_hw_power_sleep,
3226	.roothub_exec = uhci_roothub_exec,
3227	.xfer_poll = uhci_do_poll,
3228};
3229