xref: /netbsd-src/sys/dev/ic/sl811hs.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: sl811hs.c,v 1.99 2018/04/09 16:21:10 jakllsch Exp $	*/
2 
3 /*
4  * Not (c) 2007 Matthew Orgass
5  * This file is public domain, meaning anyone can make any use of part or all
6  * of this file including copying into other works without credit.  Any use,
7  * modified or not, is solely the responsibility of the user.  If this file is
8  * part of a collection then use in the collection is governed by the terms of
9  * the collection.
10  */
11 
12 /*
13  * Cypress/ScanLogic SL811HS/T USB Host Controller
14  * Datasheet, Errata, and App Note available at www.cypress.com
15  *
16  * Uses: Ratoc CFU1U PCMCIA USB Host Controller, Nereid X68k USB HC, ISA
17  * HCs.  The Ratoc CFU2 uses a different chip.
18  *
19  * This chip puts the serial in USB.  It implements USB by means of an eight
20  * bit I/O interface.  It can be used for ISA, PCMCIA/CF, parallel port,
21  * serial port, or any eight bit interface.  It has 256 bytes of memory, the
22  * first 16 of which are used for register access.  There are two sets of
23  * registers for sending individual bus transactions.  Because USB is polled,
24  * this organization means that some amount of card access must often be made
25  * when devices are attached, even if when they are not directly being used.
26  * A per-ms frame interrupt is necessary and many devices will poll with a
27  * per-frame bulk transfer.
28  *
29  * It is possible to write a little over two bytes to the chip (auto
30  * incremented) per full speed byte time on the USB.  Unfortunately,
31  * auto-increment does not work reliably so write and bus speed is
32  * approximately the same for full speed devices.
33  *
34  * In addition to the 240 byte packet size limit for isochronous transfers,
35  * this chip has no means of determining the current frame number other than
36  * getting all 1ms SOF interrupts, which is not always possible even on a fast
37  * system.  Isochronous transfers guarantee that transfers will never be
38  * retried in a later frame, so this can cause problems with devices beyond
39  * the difficulty in actually performing the transfer most frames.  I tried
40  * implementing isoc transfers and was able to play CD-derrived audio via an
41  * iMic on a 2GHz PC, however it would still be interrupted at times and
42  * once interrupted, would stay out of sync.  All isoc support has been
43  * removed.
44  *
45  * BUGS: all chip revisions have problems with low speed devices through hubs.
46  * The chip stops generating SOF with hubs that send SE0 during SOF.  See
47  * comment in dointr().  All performance enhancing features of this chip seem
48  * not to work properly, most confirmed buggy in errata doc.
49  *
50  */
51 
52 /*
53  * The hard interrupt is the main entry point.  Start, callbacks, and repeat
54  * are the only others called frequently.
55  *
56  * Since this driver attaches to pcmcia, card removal at any point should be
57  * expected and not cause panics or infinite loops.
58  */
59 
60 /*
61  * XXX TODO:
62  *   copy next output packet while transfering
63  *   usb suspend
64  *   could keep track of known values of all buffer space?
65  *   combined print/log function for errors
66  *
67  *   ub_usepolling support is untested and may not work
68  */
69 
70 #include <sys/cdefs.h>
71 __KERNEL_RCSID(0, "$NetBSD: sl811hs.c,v 1.99 2018/04/09 16:21:10 jakllsch Exp $");
72 
73 #ifdef _KERNEL_OPT
74 #include "opt_slhci.h"
75 #include "opt_usb.h"
76 #endif
77 
78 #include <sys/param.h>
79 
80 #include <sys/bus.h>
81 #include <sys/cpu.h>
82 #include <sys/device.h>
83 #include <sys/gcq.h>
84 #include <sys/intr.h>
85 #include <sys/kernel.h>
86 #include <sys/kmem.h>
87 #include <sys/proc.h>
88 #include <sys/queue.h>
89 #include <sys/sysctl.h>
90 #include <sys/systm.h>
91 
92 #include <dev/usb/usb.h>
93 #include <dev/usb/usbdi.h>
94 #include <dev/usb/usbdivar.h>
95 #include <dev/usb/usbhist.h>
96 #include <dev/usb/usb_mem.h>
97 #include <dev/usb/usbdevs.h>
98 #include <dev/usb/usbroothub.h>
99 
100 #include <dev/ic/sl811hsreg.h>
101 #include <dev/ic/sl811hsvar.h>
102 
103 #define Q_CB 0				/* Control/Bulk */
104 #define Q_NEXT_CB 1
105 #define Q_MAX_XFER Q_CB
106 #define Q_CALLBACKS 2
107 #define Q_MAX Q_CALLBACKS
108 
109 #define F_AREADY		(0x00000001)
110 #define F_BREADY		(0x00000002)
111 #define F_AINPROG		(0x00000004)
112 #define F_BINPROG		(0x00000008)
113 #define F_LOWSPEED		(0x00000010)
114 #define F_UDISABLED		(0x00000020) /* Consider disabled for USB */
115 #define F_NODEV			(0x00000040)
116 #define F_ROOTINTR		(0x00000080)
117 #define F_REALPOWER		(0x00000100) /* Actual power state */
118 #define F_POWER			(0x00000200) /* USB reported power state */
119 #define F_ACTIVE		(0x00000400)
120 #define F_CALLBACK		(0x00000800) /* Callback scheduled */
121 #define F_SOFCHECK1		(0x00001000)
122 #define F_SOFCHECK2		(0x00002000)
123 #define F_CRESET		(0x00004000) /* Reset done not reported */
124 #define F_CCONNECT		(0x00008000) /* Connect change not reported */
125 #define F_RESET			(0x00010000)
126 #define F_ISOC_WARNED		(0x00020000)
127 #define F_LSVH_WARNED		(0x00040000)
128 
129 #define F_DISABLED		(F_NODEV|F_UDISABLED)
130 #define F_CHANGE		(F_CRESET|F_CCONNECT)
131 
132 #ifdef SLHCI_TRY_LSVH
133 unsigned int slhci_try_lsvh = 1;
134 #else
135 unsigned int slhci_try_lsvh = 0;
136 #endif
137 
138 #define ADR 0
139 #define LEN 1
140 #define PID 2
141 #define DEV 3
142 #define STAT 2
143 #define CONT 3
144 
145 #define A 0
146 #define B 1
147 
148 static const uint8_t slhci_tregs[2][4] =
149 {{SL11_E0ADDR, SL11_E0LEN, SL11_E0PID, SL11_E0DEV },
150  {SL11_E1ADDR, SL11_E1LEN, SL11_E1PID, SL11_E1DEV }};
151 
152 #define PT_ROOT_CTRL	0
153 #define PT_ROOT_INTR	1
154 #define PT_CTRL_SETUP	2
155 #define PT_CTRL_DATA	3
156 #define PT_CTRL_STATUS	4
157 #define PT_INTR		5
158 #define PT_BULK		6
159 #define PT_MAX		6
160 
161 #ifdef SLHCI_DEBUG
162 #define SLHCI_MEM_ACCOUNTING
163 #endif
164 
165 /*
166  * Maximum allowable reserved bus time.  Since intr/isoc transfers have
167  * unconditional priority, this is all that ensures control and bulk transfers
168  * get a chance.  It is a single value for all frames since all transfers can
169  * use multiple consecutive frames if an error is encountered.  Note that it
170  * is not really possible to fill the bus with transfers, so this value should
171  * be on the low side.  Defaults to giving a warning unless SLHCI_NO_OVERTIME
172  * is defined.  Full time is 12000 - END_BUSTIME.
173  */
174 #ifndef SLHCI_RESERVED_BUSTIME
175 #define SLHCI_RESERVED_BUSTIME 5000
176 #endif
177 
178 /*
179  * Rate for "exceeds reserved bus time" warnings (default) or errors.
180  * Warnings only happen when an endpoint open causes the time to go above
181  * SLHCI_RESERVED_BUSTIME, not if it is already above.
182  */
183 #ifndef SLHCI_OVERTIME_WARNING_RATE
184 #define SLHCI_OVERTIME_WARNING_RATE { 60, 0 } /* 60 seconds */
185 #endif
186 static const struct timeval reserved_warn_rate = SLHCI_OVERTIME_WARNING_RATE;
187 
188 /*
189  * For EOF, the spec says 42 bit times, plus (I think) a possible hub skew of
190  * 20 bit times.  By default leave 66 bit times to start the transfer beyond
191  * the required time.  Units are full-speed bit times (a bit over 5us per 64).
192  * Only multiples of 64 are significant.
193  */
194 #define SLHCI_STANDARD_END_BUSTIME 128
195 #ifndef SLHCI_EXTRA_END_BUSTIME
196 #define SLHCI_EXTRA_END_BUSTIME 0
197 #endif
198 
199 #define SLHCI_END_BUSTIME (SLHCI_STANDARD_END_BUSTIME+SLHCI_EXTRA_END_BUSTIME)
200 
201 /*
202  * This is an approximation of the USB worst-case timings presented on p. 54 of
203  * the USB 1.1 spec translated to full speed bit times.
204  * FS = full speed with handshake, FSII = isoc in, FSIO = isoc out,
205  * FSI = isoc (worst case), LS = low speed
206  */
207 #define SLHCI_FS_CONST		114
208 #define SLHCI_FSII_CONST	92
209 #define SLHCI_FSIO_CONST	80
210 #define SLHCI_FSI_CONST		92
211 #define SLHCI_LS_CONST		804
212 #ifndef SLHCI_PRECICE_BUSTIME
213 /*
214  * These values are < 3% too high (compared to the multiply and divide) for
215  * max sized packets.
216  */
217 #define SLHCI_FS_DATA_TIME(len) (((u_int)(len)<<3)+(len)+((len)>>1))
218 #define SLHCI_LS_DATA_TIME(len) (((u_int)(len)<<6)+((u_int)(len)<<4))
219 #else
220 #define SLHCI_FS_DATA_TIME(len) (56*(len)/6)
221 #define SLHCI_LS_DATA_TIME(len) (449*(len)/6)
222 #endif
223 
224 /*
225  * Set SLHCI_WAIT_SIZE to the desired maximum size of single FS transfer
226  * to poll for after starting a transfer.  64 gets all full speed transfers.
227  * Note that even if 0 polling will occur if data equal or greater than the
228  * transfer size is copied to the chip while the transfer is in progress.
229  * Setting SLHCI_WAIT_TIME to -12000 will disable polling.
230  */
231 #ifndef SLHCI_WAIT_SIZE
232 #define SLHCI_WAIT_SIZE 8
233 #endif
234 #ifndef SLHCI_WAIT_TIME
235 #define SLHCI_WAIT_TIME (SLHCI_FS_CONST + \
236     SLHCI_FS_DATA_TIME(SLHCI_WAIT_SIZE))
237 #endif
238 const int slhci_wait_time = SLHCI_WAIT_TIME;
239 
240 #ifndef SLHCI_MAX_RETRIES
241 #define SLHCI_MAX_RETRIES 3
242 #endif
243 
244 /* Check IER values for corruption after this many unrecognized interrupts. */
245 #ifndef SLHCI_IER_CHECK_FREQUENCY
246 #ifdef SLHCI_DEBUG
247 #define SLHCI_IER_CHECK_FREQUENCY 1
248 #else
249 #define SLHCI_IER_CHECK_FREQUENCY 100
250 #endif
251 #endif
252 
253 /* Note that buffer points to the start of the buffer for this transfer.  */
254 struct slhci_pipe {
255 	struct usbd_pipe pipe;
256 	struct usbd_xfer *xfer;		/* xfer in progress */
257 	uint8_t		*buffer;	/* I/O buffer (if needed) */
258 	struct gcq 	ap;		/* All pipes */
259 	struct gcq 	to;		/* Timeout list */
260 	struct gcq 	xq;		/* Xfer queues */
261 	unsigned int	pflags;		/* Pipe flags */
262 #define PF_GONE		(0x01)		/* Pipe is on disabled device */
263 #define PF_TOGGLE 	(0x02)		/* Data toggle status */
264 #define PF_LS		(0x04)		/* Pipe is low speed */
265 #define PF_PREAMBLE	(0x08)		/* Needs preamble */
266 	Frame		to_frame;	/* Frame number for timeout */
267 	Frame		frame;		/* Frame number for intr xfer */
268 	Frame		lastframe;	/* Previous frame number for intr */
269 	uint16_t	bustime;	/* Worst case bus time usage */
270 	uint16_t	newbustime[2];	/* new bustimes (see index below) */
271 	uint8_t		tregs[4];	/* ADR, LEN, PID, DEV */
272 	uint8_t		newlen[2];	/* 0 = short data, 1 = ctrl data */
273 	uint8_t		newpid;		/* for ctrl */
274 	uint8_t		wantshort;	/* last xfer must be short */
275 	uint8_t		control;	/* Host control register settings */
276 	uint8_t		nerrs;		/* Current number of errors */
277 	uint8_t 	ptype;		/* Pipe type */
278 };
279 
280 #define SLHCI_BUS2SC(bus)	((bus)->ub_hcpriv)
281 #define SLHCI_PIPE2SC(pipe)	SLHCI_BUS2SC((pipe)->up_dev->ud_bus)
282 #define SLHCI_XFER2SC(xfer)	SLHCI_BUS2SC((xfer)->ux_bus)
283 
284 #define SLHCI_PIPE2SPIPE(pipe)	((struct slhci_pipe *)(pipe))
285 #define SLHCI_XFER2SPIPE(xfer)	SLHCI_PIPE2SPIPE((xfer)->ux_pipe)
286 
287 #define SLHCI_XFER_TYPE(x)	(SLHCI_XFER2SPIPE(xfer)->ptype)
288 
289 #ifdef SLHCI_PROFILE_TRANSFER
290 #if defined(__mips__)
291 /*
292  * MIPS cycle counter does not directly count cpu cycles but is a different
293  * fraction of cpu cycles depending on the cpu.
294  */
295 typedef uint32_t cc_type;
296 #define CC_TYPE_FMT "%u"
297 #define slhci_cc_set(x) __asm volatile ("mfc0 %[cc], $9\n\tnop\n\tnop\n\tnop" \
298     : [cc] "=r"(x))
299 #elif defined(__i386__)
300 typedef uint64_t cc_type;
301 #define CC_TYPE_FMT "%llu"
302 #define slhci_cc_set(x) __asm volatile ("rdtsc" : "=A"(x))
303 #else
304 #error "SLHCI_PROFILE_TRANSFER not implemented on this MACHINE_ARCH (see sys/dev/ic/sl811hs.c)"
305 #endif
306 struct slhci_cc_time {
307 	cc_type start;
308 	cc_type stop;
309 	unsigned int miscdata;
310 };
311 #ifndef SLHCI_N_TIMES
312 #define SLHCI_N_TIMES 200
313 #endif
314 struct slhci_cc_times {
315 	struct slhci_cc_time times[SLHCI_N_TIMES];
316 	int current;
317 	int wraparound;
318 };
319 
320 static struct slhci_cc_times t_ab[2];
321 static struct slhci_cc_times t_abdone;
322 static struct slhci_cc_times t_copy_to_dev;
323 static struct slhci_cc_times t_copy_from_dev;
324 static struct slhci_cc_times t_intr;
325 static struct slhci_cc_times t_lock;
326 static struct slhci_cc_times t_delay;
327 static struct slhci_cc_times t_hard_int;
328 static struct slhci_cc_times t_callback;
329 
330 static inline void
331 start_cc_time(struct slhci_cc_times *times, unsigned int misc) {
332 	times->times[times->current].miscdata = misc;
333 	slhci_cc_set(times->times[times->current].start);
334 }
335 static inline void
336 stop_cc_time(struct slhci_cc_times *times) {
337 	slhci_cc_set(times->times[times->current].stop);
338 	if (++times->current >= SLHCI_N_TIMES) {
339 		times->current = 0;
340 		times->wraparound = 1;
341 	}
342 }
343 
344 void slhci_dump_cc_times(int);
345 
346 void
347 slhci_dump_cc_times(int n) {
348 	struct slhci_cc_times *times;
349 	int i;
350 
351 	switch (n) {
352 	default:
353 	case 0:
354 		printf("USBA start transfer to intr:\n");
355 		times = &t_ab[A];
356 		break;
357 	case 1:
358 		printf("USBB start transfer to intr:\n");
359 		times = &t_ab[B];
360 		break;
361 	case 2:
362 		printf("abdone:\n");
363 		times = &t_abdone;
364 		break;
365 	case 3:
366 		printf("copy to device:\n");
367 		times = &t_copy_to_dev;
368 		break;
369 	case 4:
370 		printf("copy from device:\n");
371 		times = &t_copy_from_dev;
372 		break;
373 	case 5:
374 		printf("intr to intr:\n");
375 		times = &t_intr;
376 		break;
377 	case 6:
378 		printf("lock to release:\n");
379 		times = &t_lock;
380 		break;
381 	case 7:
382 		printf("delay time:\n");
383 		times = &t_delay;
384 		break;
385 	case 8:
386 		printf("hard interrupt enter to exit:\n");
387 		times = &t_hard_int;
388 		break;
389 	case 9:
390 		printf("callback:\n");
391 		times = &t_callback;
392 		break;
393 	}
394 
395 	if (times->wraparound)
396 		for (i = times->current + 1; i < SLHCI_N_TIMES; i++)
397 			printf("start " CC_TYPE_FMT " stop " CC_TYPE_FMT
398 			    " difference %8i miscdata %#x\n",
399 			    times->times[i].start, times->times[i].stop,
400 			    (int)(times->times[i].stop -
401 			    times->times[i].start), times->times[i].miscdata);
402 
403 	for (i = 0; i < times->current; i++)
404 		printf("start " CC_TYPE_FMT " stop " CC_TYPE_FMT
405 		    " difference %8i miscdata %#x\n", times->times[i].start,
406 		    times->times[i].stop, (int)(times->times[i].stop -
407 		    times->times[i].start), times->times[i].miscdata);
408 }
409 #else
410 #define start_cc_time(x, y)
411 #define stop_cc_time(x)
412 #endif /* SLHCI_PROFILE_TRANSFER */
413 
414 typedef usbd_status (*LockCallFunc)(struct slhci_softc *, struct slhci_pipe
415     *, struct usbd_xfer *);
416 
417 struct usbd_xfer * slhci_allocx(struct usbd_bus *, unsigned int);
418 void slhci_freex(struct usbd_bus *, struct usbd_xfer *);
419 static void slhci_get_lock(struct usbd_bus *, kmutex_t **);
420 
421 usbd_status slhci_transfer(struct usbd_xfer *);
422 usbd_status slhci_start(struct usbd_xfer *);
423 usbd_status slhci_root_start(struct usbd_xfer *);
424 usbd_status slhci_open(struct usbd_pipe *);
425 
426 static int slhci_roothub_ctrl(struct usbd_bus *, usb_device_request_t *,
427     void *, int);
428 
429 /*
430  * slhci_supported_rev, slhci_preinit, slhci_attach, slhci_detach,
431  * slhci_activate
432  */
433 
434 void slhci_abort(struct usbd_xfer *);
435 void slhci_close(struct usbd_pipe *);
436 void slhci_clear_toggle(struct usbd_pipe *);
437 void slhci_poll(struct usbd_bus *);
438 void slhci_done(struct usbd_xfer *);
439 void slhci_void(void *);
440 
441 /* lock entry functions */
442 
443 #ifdef SLHCI_MEM_ACCOUNTING
444 void slhci_mem_use(struct usbd_bus *, int);
445 #endif
446 
447 void slhci_reset_entry(void *);
448 usbd_status slhci_lock_call(struct slhci_softc *, LockCallFunc,
449     struct slhci_pipe *, struct usbd_xfer *);
450 void slhci_start_entry(struct slhci_softc *, struct slhci_pipe *);
451 void slhci_callback_entry(void *arg);
452 void slhci_do_callback(struct slhci_softc *, struct usbd_xfer *);
453 
454 /* slhci_intr */
455 
456 void slhci_main(struct slhci_softc *);
457 
458 /* in lock functions */
459 
460 static void slhci_write(struct slhci_softc *, uint8_t, uint8_t);
461 static uint8_t slhci_read(struct slhci_softc *, uint8_t);
462 static void slhci_write_multi(struct slhci_softc *, uint8_t, uint8_t *, int);
463 static void slhci_read_multi(struct slhci_softc *, uint8_t, uint8_t *, int);
464 
465 static void slhci_waitintr(struct slhci_softc *, int);
466 static int slhci_dointr(struct slhci_softc *);
467 static void slhci_abdone(struct slhci_softc *, int);
468 static void slhci_tstart(struct slhci_softc *);
469 static void slhci_dotransfer(struct slhci_softc *);
470 
471 static void slhci_callback(struct slhci_softc *);
472 static void slhci_enter_xfer(struct slhci_softc *, struct slhci_pipe *);
473 static void slhci_enter_xfers(struct slhci_softc *);
474 static void slhci_queue_timed(struct slhci_softc *, struct slhci_pipe *);
475 static void slhci_xfer_timer(struct slhci_softc *, struct slhci_pipe *);
476 
477 static void slhci_callback_schedule(struct slhci_softc *);
478 static void slhci_do_callback_schedule(struct slhci_softc *);
479 #if 0
480 void slhci_pollxfer(struct slhci_softc *, struct usbd_xfer *); /* XXX */
481 #endif
482 
483 static usbd_status slhci_do_poll(struct slhci_softc *, struct slhci_pipe *,
484     struct usbd_xfer *);
485 static usbd_status slhci_lsvh_warn(struct slhci_softc *, struct slhci_pipe *,
486     struct usbd_xfer *);
487 static usbd_status slhci_isoc_warn(struct slhci_softc *, struct slhci_pipe *,
488     struct usbd_xfer *);
489 static usbd_status slhci_open_pipe(struct slhci_softc *, struct slhci_pipe *,
490     struct usbd_xfer *);
491 static usbd_status slhci_close_pipe(struct slhci_softc *, struct slhci_pipe *,
492     struct usbd_xfer *);
493 static usbd_status slhci_do_abort(struct slhci_softc *, struct slhci_pipe *,
494     struct usbd_xfer *);
495 static usbd_status slhci_halt(struct slhci_softc *, struct slhci_pipe *,
496     struct usbd_xfer *);
497 
498 static void slhci_intrchange(struct slhci_softc *, uint8_t);
499 static void slhci_drain(struct slhci_softc *);
500 static void slhci_reset(struct slhci_softc *);
501 static int slhci_reserve_bustime(struct slhci_softc *, struct slhci_pipe *,
502     int);
503 static void slhci_insert(struct slhci_softc *);
504 
505 static usbd_status slhci_clear_feature(struct slhci_softc *, unsigned int);
506 static usbd_status slhci_set_feature(struct slhci_softc *, unsigned int);
507 static void slhci_get_status(struct slhci_softc *, usb_port_status_t *);
508 
509 #define	SLHCIHIST_FUNC()	USBHIST_FUNC()
510 #define	SLHCIHIST_CALLED()	USBHIST_CALLED(slhcidebug)
511 
512 #ifdef SLHCI_DEBUG
513 static int slhci_memtest(struct slhci_softc *);
514 
515 void slhci_log_buffer(struct usbd_xfer *);
516 void slhci_log_req(usb_device_request_t *);
517 void slhci_log_dumpreg(void);
518 void slhci_log_xfer(struct usbd_xfer *);
519 void slhci_log_spipe(struct slhci_pipe *);
520 void slhci_print_intr(void);
521 void slhci_log_sc(void);
522 void slhci_log_slreq(struct slhci_pipe *);
523 
524 /* Constified so you can read the values from ddb */
525 const int SLHCI_D_TRACE =	0x0001;
526 const int SLHCI_D_MSG = 	0x0002;
527 const int SLHCI_D_XFER =	0x0004;
528 const int SLHCI_D_MEM = 	0x0008;
529 const int SLHCI_D_INTR =	0x0010;
530 const int SLHCI_D_SXFER =	0x0020;
531 const int SLHCI_D_ERR = 	0x0080;
532 const int SLHCI_D_BUF = 	0x0100;
533 const int SLHCI_D_SOFT =	0x0200;
534 const int SLHCI_D_WAIT =	0x0400;
535 const int SLHCI_D_ROOT =	0x0800;
536 /* SOF/NAK alone normally ignored, SOF also needs D_INTR */
537 const int SLHCI_D_SOF =		0x1000;
538 const int SLHCI_D_NAK =		0x2000;
539 
540 int slhcidebug = 0x1cbc; /* 0xc8c; */ /* 0xffff; */ /* 0xd8c; */
541 
542 SYSCTL_SETUP(sysctl_hw_slhci_setup, "sysctl hw.slhci setup")
543 {
544 	int err;
545 	const struct sysctlnode *rnode;
546 	const struct sysctlnode *cnode;
547 
548 	err = sysctl_createv(clog, 0, NULL, &rnode,
549 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "slhci",
550 	    SYSCTL_DESCR("slhci global controls"),
551 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
552 
553 	if (err)
554 		goto fail;
555 
556 	/* control debugging printfs */
557 	err = sysctl_createv(clog, 0, &rnode, &cnode,
558 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
559 	    "debug", SYSCTL_DESCR("Enable debugging output"),
560 	    NULL, 0, &slhcidebug, sizeof(slhcidebug), CTL_CREATE, CTL_EOL);
561 	if (err)
562 		goto fail;
563 
564 	return;
565 fail:
566 	aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
567 }
568 
569 struct slhci_softc *ssc;
570 
571 #define SLHCI_DEXEC(x, y) do { if ((slhcidebug & SLHCI_ ## x)) { y; } \
572 } while (/*CONSTCOND*/ 0)
573 #define DDOLOG(f, a, b, c, d) do { KERNHIST_LOG(usbhist, f, a, b, c, d); \
574 } while (/*CONSTCOND*/0)
575 #define DLOG(x, f, a, b, c, d) SLHCI_DEXEC(x, DDOLOG(f, a, b, c, d))
576 
577 /*
578  * DDOLOGBUF logs a buffer up to 8 bytes at a time. No identifier so that we
579  * can make it a real function.
580  */
581 static void
582 DDOLOGBUF(uint8_t *buf, unsigned int length)
583 {
584 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
585 	int i;
586 
587 	for(i=0; i+8 <= length; i+=8)
588 		DDOLOG("%.4x %.4x %.4x %.4x", (buf[i] << 8) | buf[i+1],
589 		    (buf[i+2] << 8) | buf[i+3], (buf[i+4] << 8) | buf[i+5],
590 		    (buf[i+6] << 8) | buf[i+7]);
591 	if (length == i+7)
592 		DDOLOG("%.4x %.4x %.4x %.2x", (buf[i] << 8) | buf[i+1],
593 		    (buf[i+2] << 8) | buf[i+3], (buf[i+4] << 8) | buf[i+5],
594 		    buf[i+6]);
595 	else if (length == i+6)
596 		DDOLOG("%.4x %.4x %.4x", (buf[i] << 8) | buf[i+1],
597 		    (buf[i+2] << 8) | buf[i+3], (buf[i+4] << 8) | buf[i+5], 0);
598 	else if (length == i+5)
599 		DDOLOG("%.4x %.4x %.2x", (buf[i] << 8) | buf[i+1],
600 		    (buf[i+2] << 8) | buf[i+3], buf[i+4], 0);
601 	else if (length == i+4)
602 		DDOLOG("%.4x %.4x", (buf[i] << 8) | buf[i+1],
603 		    (buf[i+2] << 8) | buf[i+3], 0,0);
604 	else if (length == i+3)
605 		DDOLOG("%.4x %.2x", (buf[i] << 8) | buf[i+1], buf[i+2], 0,0);
606 	else if (length == i+2)
607 		DDOLOG("%.4x", (buf[i] << 8) | buf[i+1], 0,0,0);
608 	else if (length == i+1)
609 		DDOLOG("%.2x", buf[i], 0,0,0);
610 }
611 #define DLOGBUF(x, b, l) SLHCI_DEXEC(x, DDOLOGBUF(b, l))
612 
613 #define DDOLOGCTRL(x)	do {						\
614     DDOLOG("CTRL suspend=%jd", !!((x) & SL11_CTRL_SUSPEND), 0, 0, 0);	\
615     DDOLOG("CTRL ls     =%jd  jk     =%jd  reset  =%jd  sof    =%jd",	\
616 	!!((x) & SL11_CTRL_LOWSPEED), !!((x) & SL11_CTRL_JKSTATE),	\
617 	!!((x) & SL11_CTRL_RESETENGINE), !!((x) & SL11_CTRL_ENABLESOF));\
618 } while (0)
619 
620 #define DDOLOGISR(r)	do {						\
621     DDOLOG("ISR  data   =%jd  det/res=%jd  insert =%jd  sof    =%jd",	\
622 	!!((r) & SL11_ISR_DATA), !!((r) & SL11_ISR_RESUME),		\
623 	!!((r) & SL11_ISR_INSERT), !!!!((r) & SL11_ISR_SOF));		\
624     DDOLOG("ISR             babble =%jd  usbb   =%jd  usba   =%jd",	\
625 	!!((r) & SL11_ISR_BABBLE), !!((r) & SL11_ISR_USBB),		\
626 	!!((r) & SL11_ISR_USBA), 0);					\
627 } while (0)
628 
629 #define DDOLOGIER(r)	do {						\
630     DDOLOG("IER              det/res=%d  insert =%d  sof    =%d",	\
631 	!!((r) & SL11_IER_RESUME),					\
632 	!!((r) & SL11_IER_INSERT), !!!!((r) & SL11_IER_SOF), 0);		\
633     DDOLOG("IER              babble =%d  usbb   =%d  usba   =%d",	\
634 	!!((r) & SL11_IER_BABBLE), !!((r) & SL11_IER_USBB),		\
635 	!!((r) & SL11_IER_USBA), 0);					\
636 } while (0)
637 
638 #define DDOLOGSTATUS(s)	do {						\
639     DDOLOG("STAT stall   =%d  nak     =%d  overflow =%d  setup   =%d",	\
640 	!!((s) & SL11_EPSTAT_STALL), !!((s) & SL11_EPSTAT_NAK),		\
641 	!!((s) & SL11_EPSTAT_OVERFLOW), !!((s) & SL11_EPSTAT_SETUP));	\
642     DDOLOG("STAT sequence=%d  timeout =%d  error    =%d  ack     =%d",	\
643 	!!((s) & SL11_EPSTAT_SEQUENCE),	!!((s) & SL11_EPSTAT_TIMEOUT),	\
644 	!!((s) & SL11_EPSTAT_ERROR), !!((s) & SL11_EPSTAT_ACK));	\
645 } while (0)
646 
647 #define DDOLOGEPCTRL(r)	do {						\
648     DDOLOG("CTRL preamble=%d  toggle  =%d  sof     =%d  iso     =%d",	\
649 	!!((r) & SL11_EPCTRL_PREAMBLE), !!((r) & SL11_EPCTRL_DATATOGGLE),\
650 	!!((r) & SL11_EPCTRL_SOF), !!((r) & SL11_EPCTRL_ISO));		\
651     DDOLOG("CTRL              out     =%d  enable  =%d  arm     =%d",	\
652 	!!((r) & SL11_EPCTRL_DIRECTION),				\
653 	!!((r) & SL11_EPCTRL_ENABLE), !!((r) & SL11_EPCTRL_ARM), 0);	\
654 } while (0)
655 
656 #define DDOLOGEPSTAT(r)	do {						\
657     DDOLOG("STAT stall   =%d  nak     =%d  overflow =%d  setup   =%d",	\
658 	!!((r) & SL11_EPSTAT_STALL), !!((r) & SL11_EPSTAT_NAK),		\
659 	!!((r) & SL11_EPSTAT_OVERFLOW), !!((r) & SL11_EPSTAT_SETUP));	\
660     DDOLOG("STAT sequence=%d  timeout =%d  error    =%d  ack   =%d",	\
661 	!!((r) & SL11_EPSTAT_SEQUENCE), !!((r) & SL11_EPSTAT_TIMEOUT),	\
662 	!!((r) & SL11_EPSTAT_ERROR), !!((r) & SL11_EPSTAT_ACK));	\
663 } while (0)
664 #else /* now !SLHCI_DEBUG */
665 #define slhcidebug 0
666 #define slhci_log_spipe(spipe) ((void)0)
667 #define slhci_log_xfer(xfer) ((void)0)
668 #define SLHCI_DEXEC(x, y) ((void)0)
669 #define DDOLOG(f, a, b, c, d) ((void)0)
670 #define DLOG(x, f, a, b, c, d) ((void)0)
671 #define DDOLOGBUF(b, l) ((void)0)
672 #define DLOGBUF(x, b, l) ((void)0)
673 #define DDOLOGCTRL(x) ((void)0)
674 #define DDOLOGISR(r) ((void)0)
675 #define DDOLOGIER(r) ((void)0)
676 #define DDOLOGSTATUS(s) ((void)0)
677 #define DDOLOGEPCTRL(r) ((void)0)
678 #define DDOLOGEPSTAT(r) ((void)0)
679 #endif /* SLHCI_DEBUG */
680 
681 #ifdef DIAGNOSTIC
682 #define LK_SLASSERT(exp, sc, spipe, xfer, ext) do {			\
683 	if (!(exp)) {							\
684 		printf("%s: assertion %s failed line %u function %s!"	\
685 		" halted\n", SC_NAME(sc), #exp, __LINE__, __func__);\
686 		slhci_halt(sc, spipe, xfer);				\
687 		ext;							\
688 	}								\
689 } while (/*CONSTCOND*/0)
690 #define UL_SLASSERT(exp, sc, spipe, xfer, ext) do {			\
691 	if (!(exp)) {							\
692 		printf("%s: assertion %s failed line %u function %s!"	\
693 		" halted\n", SC_NAME(sc), #exp, __LINE__, __func__);	\
694 		slhci_lock_call(sc, &slhci_halt, spipe, xfer);		\
695 		ext;							\
696 	}								\
697 } while (/*CONSTCOND*/0)
698 #else
699 #define LK_SLASSERT(exp, sc, spipe, xfer, ext) ((void)0)
700 #define UL_SLASSERT(exp, sc, spipe, xfer, ext) ((void)0)
701 #endif
702 
703 const struct usbd_bus_methods slhci_bus_methods = {
704 	.ubm_open = slhci_open,
705 	.ubm_softint= slhci_void,
706 	.ubm_dopoll = slhci_poll,
707 	.ubm_allocx = slhci_allocx,
708 	.ubm_freex = slhci_freex,
709 	.ubm_getlock = slhci_get_lock,
710 	.ubm_rhctrl = slhci_roothub_ctrl,
711 };
712 
713 const struct usbd_pipe_methods slhci_pipe_methods = {
714 	.upm_transfer = slhci_transfer,
715 	.upm_start = slhci_start,
716 	.upm_abort = slhci_abort,
717 	.upm_close = slhci_close,
718 	.upm_cleartoggle = slhci_clear_toggle,
719 	.upm_done = slhci_done,
720 };
721 
722 const struct usbd_pipe_methods slhci_root_methods = {
723 	.upm_transfer = slhci_transfer,
724 	.upm_start = slhci_root_start,
725 	.upm_abort = slhci_abort,
726 	.upm_close = (void (*)(struct usbd_pipe *))slhci_void, /* XXX safe? */
727 	.upm_cleartoggle = slhci_clear_toggle,
728 	.upm_done = slhci_done,
729 };
730 
731 /* Queue inlines */
732 
733 #define GOT_FIRST_TO(tvar, t) \
734     GCQ_GOT_FIRST_TYPED(tvar, &(t)->to, struct slhci_pipe, to)
735 
736 #define FIND_TO(var, t, tvar, cond) \
737     GCQ_FIND_TYPED(var, &(t)->to, tvar, struct slhci_pipe, to, cond)
738 
739 #define FOREACH_AP(var, t, tvar) \
740     GCQ_FOREACH_TYPED(var, &(t)->ap, tvar, struct slhci_pipe, ap)
741 
742 #define GOT_FIRST_TIMED_COND(tvar, t, cond) \
743     GCQ_GOT_FIRST_COND_TYPED(tvar, &(t)->timed, struct slhci_pipe, xq, cond)
744 
745 #define GOT_FIRST_CB(tvar, t) \
746     GCQ_GOT_FIRST_TYPED(tvar, &(t)->q[Q_CB], struct slhci_pipe, xq)
747 
748 #define DEQUEUED_CALLBACK(tvar, t) \
749     GCQ_DEQUEUED_FIRST_TYPED(tvar, &(t)->q[Q_CALLBACKS], struct slhci_pipe, xq)
750 
751 #define FIND_TIMED(var, t, tvar, cond) \
752    GCQ_FIND_TYPED(var, &(t)->timed, tvar, struct slhci_pipe, xq, cond)
753 
754 #define DEQUEUED_WAITQ(tvar, sc) \
755     GCQ_DEQUEUED_FIRST_TYPED(tvar, &(sc)->sc_waitq, struct slhci_pipe, xq)
756 
757 static inline void
758 enter_waitq(struct slhci_softc *sc, struct slhci_pipe *spipe)
759 {
760 	gcq_insert_tail(&sc->sc_waitq, &spipe->xq);
761 }
762 
763 static inline void
764 enter_q(struct slhci_transfers *t, struct slhci_pipe *spipe, int i)
765 {
766 	gcq_insert_tail(&t->q[i], &spipe->xq);
767 }
768 
769 static inline void
770 enter_callback(struct slhci_transfers *t, struct slhci_pipe *spipe)
771 {
772 	gcq_insert_tail(&t->q[Q_CALLBACKS], &spipe->xq);
773 }
774 
775 static inline void
776 enter_all_pipes(struct slhci_transfers *t, struct slhci_pipe *spipe)
777 {
778 	gcq_insert_tail(&t->ap, &spipe->ap);
779 }
780 
781 /* Start out of lock functions. */
782 
783 struct usbd_xfer *
784 slhci_allocx(struct usbd_bus *bus, unsigned int nframes)
785 {
786 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
787 	struct usbd_xfer *xfer;
788 
789 	xfer = kmem_zalloc(sizeof(*xfer), KM_SLEEP);
790 
791 	DLOG(D_MEM, "allocx %#jx", (uintptr_t)xfer, 0,0,0);
792 
793 #ifdef SLHCI_MEM_ACCOUNTING
794 	slhci_mem_use(bus, 1);
795 #endif
796 #ifdef DIAGNOSTIC
797 	if (xfer != NULL)
798 		xfer->ux_state = XFER_BUSY;
799 #endif
800 	return xfer;
801 }
802 
803 void
804 slhci_freex(struct usbd_bus *bus, struct usbd_xfer *xfer)
805 {
806 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
807 	DLOG(D_MEM, "freex xfer %#jx spipe %#jx",
808 	    (uintptr_t)xfer, (uintptr_t)xfer->ux_pipe,0,0);
809 
810 #ifdef SLHCI_MEM_ACCOUNTING
811 	slhci_mem_use(bus, -1);
812 #endif
813 #ifdef DIAGNOSTIC
814 	if (xfer->ux_state != XFER_BUSY) {
815 		struct slhci_softc *sc = SLHCI_BUS2SC(bus);
816 		printf("%s: slhci_freex: xfer=%p not busy, %#08x halted\n",
817 		    SC_NAME(sc), xfer, xfer->ux_state);
818 		DDOLOG("xfer=%p not busy, %#08x halted\n", xfer,
819 		    xfer->ux_state, 0, 0);
820 		slhci_lock_call(sc, &slhci_halt, NULL, NULL);
821 		return;
822 	}
823 	xfer->ux_state = XFER_FREE;
824 #endif
825 
826 	kmem_free(xfer, sizeof(*xfer));
827 }
828 
829 static void
830 slhci_get_lock(struct usbd_bus *bus, kmutex_t **lock)
831 {
832 	struct slhci_softc *sc = SLHCI_BUS2SC(bus);
833 
834 	*lock = &sc->sc_lock;
835 }
836 
837 usbd_status
838 slhci_transfer(struct usbd_xfer *xfer)
839 {
840 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
841 	struct slhci_softc *sc = SLHCI_XFER2SC(xfer);
842 	usbd_status error;
843 
844 	DLOG(D_TRACE, "transfer type %jd xfer %#jx spipe %#jx ",
845 	    SLHCI_XFER_TYPE(xfer), (uintptr_t)xfer, (uintptr_t)xfer->ux_pipe,
846 	    0);
847 
848 	/* Insert last in queue */
849 	mutex_enter(&sc->sc_lock);
850 	error = usb_insert_transfer(xfer);
851 	mutex_exit(&sc->sc_lock);
852 	if (error) {
853 		if (error != USBD_IN_PROGRESS)
854 			DLOG(D_ERR, "usb_insert_transfer returns %jd!", error,
855 			    0,0,0);
856 		return error;
857 	}
858 
859 	/*
860 	 * Pipe isn't running (otherwise error would be USBD_INPROG),
861 	 * so start it first.
862 	 */
863 
864 	/*
865 	 * Start will take the lock.
866 	 */
867 	error = xfer->ux_pipe->up_methods->upm_start(SIMPLEQ_FIRST(&xfer->ux_pipe->up_queue));
868 
869 	return error;
870 }
871 
872 /* It is not safe for start to return anything other than USBD_INPROG. */
873 usbd_status
874 slhci_start(struct usbd_xfer *xfer)
875 {
876 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
877 	struct slhci_softc *sc = SLHCI_XFER2SC(xfer);
878 	struct usbd_pipe *pipe = xfer->ux_pipe;
879 	struct slhci_pipe *spipe = SLHCI_PIPE2SPIPE(pipe);
880 	struct slhci_transfers *t = &sc->sc_transfers;
881 	usb_endpoint_descriptor_t *ed = pipe->up_endpoint->ue_edesc;
882 	unsigned int max_packet;
883 
884 	mutex_enter(&sc->sc_lock);
885 
886 	max_packet = UGETW(ed->wMaxPacketSize);
887 
888 	DLOG(D_TRACE, "transfer type %jd start xfer %#jx spipe %#jx length %jd",
889 	    spipe->ptype, (uintptr_t)xfer, (uintptr_t)spipe, xfer->ux_length);
890 
891 	/* root transfers use slhci_root_start */
892 
893 	KASSERT(spipe->xfer == NULL); /* not SLASSERT */
894 
895 	xfer->ux_actlen = 0;
896 	xfer->ux_status = USBD_IN_PROGRESS;
897 
898 	spipe->xfer = xfer;
899 
900 	spipe->nerrs = 0;
901 	spipe->frame = t->frame;
902 	spipe->control = SL11_EPCTRL_ARM_ENABLE;
903 	spipe->tregs[DEV] = pipe->up_dev->ud_addr;
904 	spipe->tregs[PID] = spipe->newpid = UE_GET_ADDR(ed->bEndpointAddress)
905 	    | (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN ? SL11_PID_IN :
906 	    SL11_PID_OUT);
907 	spipe->newlen[0] = xfer->ux_length % max_packet;
908 	spipe->newlen[1] = min(xfer->ux_length, max_packet);
909 
910 	if (spipe->ptype == PT_BULK || spipe->ptype == PT_INTR) {
911 		if (spipe->pflags & PF_TOGGLE)
912 			spipe->control |= SL11_EPCTRL_DATATOGGLE;
913 		spipe->tregs[LEN] = spipe->newlen[1];
914 		if (spipe->tregs[LEN])
915 			spipe->buffer = xfer->ux_buf;
916 		else
917 			spipe->buffer = NULL;
918 		spipe->lastframe = t->frame;
919 		if (spipe->ptype == PT_INTR) {
920 			spipe->frame = spipe->lastframe +
921 			    spipe->pipe.up_interval;
922 		}
923 
924 #if defined(DEBUG) || defined(SLHCI_DEBUG)
925 		if (__predict_false(spipe->ptype == PT_INTR &&
926 		    xfer->ux_length > spipe->tregs[LEN])) {
927 			printf("%s: Long INTR transfer not supported!\n",
928 			    SC_NAME(sc));
929 			DDOLOG("Long INTR transfer not supported!", 0, 0, 0, 0);
930 			xfer->ux_status = USBD_INVAL;
931 		}
932 #endif
933 	} else {
934 		/* ptype may be currently set to any control transfer type. */
935 		SLHCI_DEXEC(D_TRACE, slhci_log_xfer(xfer));
936 
937 		/* SETUP contains IN/OUT bits also */
938 		spipe->tregs[PID] |= SL11_PID_SETUP;
939 		spipe->tregs[LEN] = 8;
940 		spipe->buffer = (uint8_t *)&xfer->ux_request;
941 		DLOGBUF(D_XFER, spipe->buffer, spipe->tregs[LEN]);
942 		spipe->ptype = PT_CTRL_SETUP;
943 		spipe->newpid &= ~SL11_PID_BITS;
944 		if (xfer->ux_length == 0 ||
945 		    (xfer->ux_request.bmRequestType & UT_READ))
946 			spipe->newpid |= SL11_PID_IN;
947 		else
948 			spipe->newpid |= SL11_PID_OUT;
949 	}
950 
951 	if (xfer->ux_flags & USBD_FORCE_SHORT_XFER &&
952 	    spipe->tregs[LEN] == max_packet &&
953 	    (spipe->newpid & SL11_PID_BITS) == SL11_PID_OUT)
954 		spipe->wantshort = 1;
955 	else
956 		spipe->wantshort = 0;
957 
958 	/*
959 	 * The goal of newbustime and newlen is to avoid bustime calculation
960 	 * in the interrupt.  The calculations are not too complex, but they
961 	 * complicate the conditional logic somewhat and doing them all in the
962 	 * same place shares constants. Index 0 is "short length" for bulk and
963 	 * ctrl data and 1 is "full length" for ctrl data (bulk/intr are
964 	 * already set to full length).
965 	 */
966 	if (spipe->pflags & PF_LS) {
967 		/*
968 		 * Setting PREAMBLE for directly connected LS devices will
969 		 * lock up the chip.
970 		 */
971 		if (spipe->pflags & PF_PREAMBLE)
972 			spipe->control |= SL11_EPCTRL_PREAMBLE;
973 		if (max_packet <= 8) {
974 			spipe->bustime = SLHCI_LS_CONST +
975 			    SLHCI_LS_DATA_TIME(spipe->tregs[LEN]);
976 			spipe->newbustime[0] = SLHCI_LS_CONST +
977 			    SLHCI_LS_DATA_TIME(spipe->newlen[0]);
978 			spipe->newbustime[1] = SLHCI_LS_CONST +
979 			    SLHCI_LS_DATA_TIME(spipe->newlen[1]);
980 		} else
981 			xfer->ux_status = USBD_INVAL;
982 	} else {
983 		UL_SLASSERT(pipe->up_dev->ud_speed == USB_SPEED_FULL, sc,
984 		    spipe, xfer, return USBD_IN_PROGRESS);
985 		if (max_packet <= SL11_MAX_PACKET_SIZE) {
986 			spipe->bustime = SLHCI_FS_CONST +
987 			    SLHCI_FS_DATA_TIME(spipe->tregs[LEN]);
988 			spipe->newbustime[0] = SLHCI_FS_CONST +
989 			    SLHCI_FS_DATA_TIME(spipe->newlen[0]);
990 			spipe->newbustime[1] = SLHCI_FS_CONST +
991 			    SLHCI_FS_DATA_TIME(spipe->newlen[1]);
992 		} else
993 			xfer->ux_status = USBD_INVAL;
994 	}
995 
996 	/*
997 	 * The datasheet incorrectly indicates that DIRECTION is for
998 	 * "transmit to host".  It is for OUT and SETUP.  The app note
999 	 * describes its use correctly.
1000 	 */
1001 	if ((spipe->tregs[PID] & SL11_PID_BITS) != SL11_PID_IN)
1002 		spipe->control |= SL11_EPCTRL_DIRECTION;
1003 
1004 	slhci_start_entry(sc, spipe);
1005 
1006 	mutex_exit(&sc->sc_lock);
1007 
1008 	return USBD_IN_PROGRESS;
1009 }
1010 
1011 usbd_status
1012 slhci_root_start(struct usbd_xfer *xfer)
1013 {
1014 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1015 	struct slhci_softc *sc;
1016 	struct slhci_pipe *spipe __diagused;
1017 
1018 	spipe = SLHCI_PIPE2SPIPE(xfer->ux_pipe);
1019 	sc = SLHCI_XFER2SC(xfer);
1020 
1021 	struct slhci_transfers *t = &sc->sc_transfers;
1022 
1023 	LK_SLASSERT(spipe != NULL && xfer != NULL, sc, spipe, xfer, return
1024 	    USBD_CANCELLED);
1025 
1026 	DLOG(D_TRACE, "transfer type %jd start",
1027 	    SLHCI_XFER_TYPE(xfer), 0, 0, 0);
1028 
1029 	KASSERT(spipe->ptype == PT_ROOT_INTR);
1030 
1031 	mutex_enter(&sc->sc_intr_lock);
1032 	t->rootintr = xfer;
1033 	mutex_exit(&sc->sc_intr_lock);
1034 
1035 	return USBD_IN_PROGRESS;
1036 }
1037 
1038 usbd_status
1039 slhci_open(struct usbd_pipe *pipe)
1040 {
1041 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1042 	struct usbd_device *dev;
1043 	struct slhci_softc *sc;
1044 	struct slhci_pipe *spipe;
1045 	usb_endpoint_descriptor_t *ed;
1046 	unsigned int max_packet, pmaxpkt;
1047 	uint8_t rhaddr;
1048 
1049 	dev = pipe->up_dev;
1050 	sc = SLHCI_PIPE2SC(pipe);
1051 	spipe = SLHCI_PIPE2SPIPE(pipe);
1052 	ed = pipe->up_endpoint->ue_edesc;
1053 	rhaddr = dev->ud_bus->ub_rhaddr;
1054 
1055 	DLOG(D_TRACE, "slhci_open(addr=%jd,ep=%jd,rootaddr=%jd)",
1056 		dev->ud_addr, ed->bEndpointAddress, rhaddr, 0);
1057 
1058 	spipe->pflags = 0;
1059 	spipe->frame = 0;
1060 	spipe->lastframe = 0;
1061 	spipe->xfer = NULL;
1062 	spipe->buffer = NULL;
1063 
1064 	gcq_init(&spipe->ap);
1065 	gcq_init(&spipe->to);
1066 	gcq_init(&spipe->xq);
1067 
1068 	/*
1069 	 * The endpoint descriptor will not have been set up yet in the case
1070 	 * of the standard control pipe, so the max packet checks are also
1071 	 * necessary in start.
1072 	 */
1073 
1074 	max_packet = UGETW(ed->wMaxPacketSize);
1075 
1076 	if (dev->ud_speed == USB_SPEED_LOW) {
1077 		spipe->pflags |= PF_LS;
1078 		if (dev->ud_myhub->ud_addr != rhaddr) {
1079 			spipe->pflags |= PF_PREAMBLE;
1080 			if (!slhci_try_lsvh)
1081 				return slhci_lock_call(sc, &slhci_lsvh_warn,
1082 				    spipe, NULL);
1083 		}
1084 		pmaxpkt = 8;
1085 	} else
1086 		pmaxpkt = SL11_MAX_PACKET_SIZE;
1087 
1088 	if (max_packet > pmaxpkt) {
1089 		DLOG(D_ERR, "packet too large! size %jd spipe %#jx", max_packet,
1090 		    (uintptr_t)spipe, 0,0);
1091 		return USBD_INVAL;
1092 	}
1093 
1094 	if (dev->ud_addr == rhaddr) {
1095 		switch (ed->bEndpointAddress) {
1096 		case USB_CONTROL_ENDPOINT:
1097 			spipe->ptype = PT_ROOT_CTRL;
1098 			pipe->up_interval = 0;
1099 			pipe->up_methods = &roothub_ctrl_methods;
1100 			break;
1101 		case UE_DIR_IN | USBROOTHUB_INTR_ENDPT:
1102 			spipe->ptype = PT_ROOT_INTR;
1103 			pipe->up_interval = 1;
1104 			pipe->up_methods = &slhci_root_methods;
1105 			break;
1106 		default:
1107 			printf("%s: Invalid root endpoint!\n", SC_NAME(sc));
1108 			DDOLOG("Invalid root endpoint", 0, 0, 0, 0);
1109 			return USBD_INVAL;
1110 		}
1111 		return USBD_NORMAL_COMPLETION;
1112 	} else {
1113 		switch (ed->bmAttributes & UE_XFERTYPE) {
1114 		case UE_CONTROL:
1115 			spipe->ptype = PT_CTRL_SETUP;
1116 			pipe->up_interval = 0;
1117 			break;
1118 		case UE_INTERRUPT:
1119 			spipe->ptype = PT_INTR;
1120 			if (pipe->up_interval == USBD_DEFAULT_INTERVAL)
1121 				pipe->up_interval = ed->bInterval;
1122 			break;
1123 		case UE_ISOCHRONOUS:
1124 			return slhci_lock_call(sc, &slhci_isoc_warn, spipe,
1125 			    NULL);
1126 		case UE_BULK:
1127 			spipe->ptype = PT_BULK;
1128 			pipe->up_interval = 0;
1129 			break;
1130 		}
1131 
1132 		DLOG(D_MSG, "open pipe type %jd interval %jd", spipe->ptype,
1133 		    pipe->up_interval, 0,0);
1134 
1135 		pipe->up_methods = __UNCONST(&slhci_pipe_methods);
1136 
1137 		return slhci_lock_call(sc, &slhci_open_pipe, spipe, NULL);
1138 	}
1139 }
1140 
1141 int
1142 slhci_supported_rev(uint8_t rev)
1143 {
1144 	return rev >= SLTYPE_SL811HS_R12 && rev <= SLTYPE_SL811HS_R15;
1145 }
1146 
1147 /*
1148  * Must be called before the ISR is registered. Interrupts can be shared so
1149  * slhci_intr could be called as soon as the ISR is registered.
1150  * Note max_current argument is actual current, but stored as current/2
1151  */
1152 void
1153 slhci_preinit(struct slhci_softc *sc, PowerFunc pow, bus_space_tag_t iot,
1154     bus_space_handle_t ioh, uint16_t max_current, uint32_t stride)
1155 {
1156 	struct slhci_transfers *t;
1157 	int i;
1158 
1159 	t = &sc->sc_transfers;
1160 
1161 #ifdef SLHCI_DEBUG
1162 	ssc = sc;
1163 #endif
1164 
1165 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
1166 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_USB);
1167 
1168 	/* sc->sc_ier = 0;	*/
1169 	/* t->rootintr = NULL;	*/
1170 	t->flags = F_NODEV|F_UDISABLED;
1171 	t->pend = INT_MAX;
1172 	KASSERT(slhci_wait_time != INT_MAX);
1173 	t->len[0] = t->len[1] = -1;
1174 	if (max_current > 500)
1175 		max_current = 500;
1176 	t->max_current = (uint8_t)(max_current / 2);
1177 	sc->sc_enable_power = pow;
1178 	sc->sc_iot = iot;
1179 	sc->sc_ioh = ioh;
1180 	sc->sc_stride = stride;
1181 
1182 	KASSERT(Q_MAX+1 == sizeof(t->q) / sizeof(t->q[0]));
1183 
1184 	for (i = 0; i <= Q_MAX; i++)
1185 		gcq_init_head(&t->q[i]);
1186 	gcq_init_head(&t->timed);
1187 	gcq_init_head(&t->to);
1188 	gcq_init_head(&t->ap);
1189 	gcq_init_head(&sc->sc_waitq);
1190 }
1191 
1192 int
1193 slhci_attach(struct slhci_softc *sc)
1194 {
1195 	struct slhci_transfers *t;
1196 	const char *rev;
1197 
1198 	t = &sc->sc_transfers;
1199 
1200 	/* Detect and check the controller type */
1201 	t->sltype = SL11_GET_REV(slhci_read(sc, SL11_REV));
1202 
1203 	/* SL11H not supported */
1204 	if (!slhci_supported_rev(t->sltype)) {
1205 		if (t->sltype == SLTYPE_SL11H)
1206 			printf("%s: SL11H unsupported or bus error!\n",
1207 			    SC_NAME(sc));
1208 		else
1209 			printf("%s: Unknown chip revision!\n", SC_NAME(sc));
1210 		return -1;
1211 	}
1212 
1213 #ifdef SLHCI_DEBUG
1214 	if (slhci_memtest(sc)) {
1215 		printf("%s: memory/bus error!\n", SC_NAME(sc));
1216 		return -1;
1217 	}
1218 #endif
1219 
1220 	callout_init(&sc->sc_timer, CALLOUT_MPSAFE);
1221 	callout_setfunc(&sc->sc_timer, slhci_reset_entry, sc);
1222 
1223 	/*
1224 	 * It is not safe to call the soft interrupt directly as
1225 	 * usb_schedsoftintr does in the ub_usepolling case (due to locking).
1226 	 */
1227 	sc->sc_cb_softintr = softint_establish(SOFTINT_NET,
1228 	    slhci_callback_entry, sc);
1229 
1230 	if (t->sltype == SLTYPE_SL811HS_R12)
1231 		rev = "(rev 1.2)";
1232 	else if (t->sltype == SLTYPE_SL811HS_R14)
1233 		rev = "(rev 1.4 or 1.5)";
1234 	else
1235 		rev = "(unknown revision)";
1236 
1237 	aprint_normal("%s: ScanLogic SL811HS/T USB Host Controller %s\n",
1238 	    SC_NAME(sc), rev);
1239 
1240 	aprint_normal("%s: Max Current %u mA (value by code, not by probe)\n",
1241 	    SC_NAME(sc), t->max_current * 2);
1242 
1243 #if defined(SLHCI_DEBUG) || defined(SLHCI_NO_OVERTIME) || \
1244     defined(SLHCI_TRY_LSVH) || defined(SLHCI_PROFILE_TRANSFER)
1245 	aprint_normal("%s: driver options:"
1246 #ifdef SLHCI_DEBUG
1247 	" SLHCI_DEBUG"
1248 #endif
1249 #ifdef SLHCI_TRY_LSVH
1250 	" SLHCI_TRY_LSVH"
1251 #endif
1252 #ifdef SLHCI_NO_OVERTIME
1253 	" SLHCI_NO_OVERTIME"
1254 #endif
1255 #ifdef SLHCI_PROFILE_TRANSFER
1256 	" SLHCI_PROFILE_TRANSFER"
1257 #endif
1258 	"\n", SC_NAME(sc));
1259 #endif
1260 	sc->sc_bus.ub_revision = USBREV_1_1;
1261 	sc->sc_bus.ub_methods = __UNCONST(&slhci_bus_methods);
1262 	sc->sc_bus.ub_pipesize = sizeof(struct slhci_pipe);
1263 	sc->sc_bus.ub_usedma = false;
1264 
1265 	if (!sc->sc_enable_power)
1266 		t->flags |= F_REALPOWER;
1267 
1268 	t->flags |= F_ACTIVE;
1269 
1270 	/* Attach usb and uhub. */
1271 	sc->sc_child = config_found(SC_DEV(sc), &sc->sc_bus, usbctlprint);
1272 
1273 	if (!sc->sc_child)
1274 		return -1;
1275 	else
1276 		return 0;
1277 }
1278 
1279 int
1280 slhci_detach(struct slhci_softc *sc, int flags)
1281 {
1282 	struct slhci_transfers *t;
1283 	int ret;
1284 
1285 	t = &sc->sc_transfers;
1286 
1287 	/* By this point bus access is no longer allowed. */
1288 
1289 	KASSERT(!(t->flags & F_ACTIVE));
1290 
1291 	/*
1292 	 * To be MPSAFE is not sufficient to cancel callouts and soft
1293 	 * interrupts and assume they are dead since the code could already be
1294 	 * running or about to run.  Wait until they are known to be done.
1295 	 */
1296 	while (t->flags & (F_RESET|F_CALLBACK))
1297 		tsleep(&sc, PPAUSE, "slhci_detach", hz);
1298 
1299 	softint_disestablish(sc->sc_cb_softintr);
1300 
1301 	mutex_destroy(&sc->sc_lock);
1302 	mutex_destroy(&sc->sc_intr_lock);
1303 
1304 	ret = 0;
1305 
1306 	if (sc->sc_child)
1307 		ret = config_detach(sc->sc_child, flags);
1308 
1309 #ifdef SLHCI_MEM_ACCOUNTING
1310 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1311 	if (sc->sc_mem_use) {
1312 		printf("%s: Memory still in use after detach! mem_use (count)"
1313 		    " = %d\n", SC_NAME(sc), sc->sc_mem_use);
1314 		DDOLOG("Memory still in use after detach! mem_use (count)"
1315 		    " = %d", sc->sc_mem_use, 0, 0, 0);
1316 	}
1317 #endif
1318 
1319 	return ret;
1320 }
1321 
1322 int
1323 slhci_activate(device_t self, enum devact act)
1324 {
1325 	struct slhci_softc *sc = device_private(self);
1326 
1327 	switch (act) {
1328 	case DVACT_DEACTIVATE:
1329 		slhci_lock_call(sc, &slhci_halt, NULL, NULL);
1330 		return 0;
1331 	default:
1332 		return EOPNOTSUPP;
1333 	}
1334 }
1335 
1336 void
1337 slhci_abort(struct usbd_xfer *xfer)
1338 {
1339 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1340 	struct slhci_softc *sc;
1341 	struct slhci_pipe *spipe;
1342 
1343 	spipe = SLHCI_PIPE2SPIPE(xfer->ux_pipe);
1344 
1345 	if (spipe == NULL)
1346 		goto callback;
1347 
1348 	sc = SLHCI_XFER2SC(xfer);
1349 	KASSERT(mutex_owned(&sc->sc_lock));
1350 
1351 	DLOG(D_TRACE, "transfer type %jd abort xfer %#jx spipe %#jx "
1352 	    " spipe->xfer %#jx", spipe->ptype, (uintptr_t)xfer,
1353 	    (uintptr_t)spipe, (uintptr_t)spipe->xfer);
1354 
1355 	slhci_lock_call(sc, &slhci_do_abort, spipe, xfer);
1356 
1357 callback:
1358 	xfer->ux_status = USBD_CANCELLED;
1359 	usb_transfer_complete(xfer);
1360 }
1361 
1362 void
1363 slhci_close(struct usbd_pipe *pipe)
1364 {
1365 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1366 	struct slhci_softc *sc;
1367 	struct slhci_pipe *spipe;
1368 
1369 	sc = SLHCI_PIPE2SC(pipe);
1370 	spipe = SLHCI_PIPE2SPIPE(pipe);
1371 
1372 	DLOG(D_TRACE, "transfer type %jd close spipe %#jx spipe->xfer %#jx",
1373 	    spipe->ptype, (uintptr_t)spipe, (uintptr_t)spipe->xfer, 0);
1374 
1375 	slhci_lock_call(sc, &slhci_close_pipe, spipe, NULL);
1376 }
1377 
1378 void
1379 slhci_clear_toggle(struct usbd_pipe *pipe)
1380 {
1381 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1382 	struct slhci_pipe *spipe;
1383 
1384 	spipe = SLHCI_PIPE2SPIPE(pipe);
1385 
1386 	DLOG(D_TRACE, "transfer type %jd toggle spipe %#jx", spipe->ptype,
1387 	    (uintptr_t)spipe, 0, 0);
1388 
1389 	spipe->pflags &= ~PF_TOGGLE;
1390 
1391 #ifdef DIAGNOSTIC
1392 	if (spipe->xfer != NULL) {
1393 		struct slhci_softc *sc = (struct slhci_softc
1394 		    *)pipe->up_dev->ud_bus;
1395 
1396 		printf("%s: Clear toggle on transfer in progress! halted\n",
1397 		    SC_NAME(sc));
1398 		DDOLOG("Clear toggle on transfer in progress! halted",
1399 		    0, 0, 0, 0);
1400 		slhci_halt(sc, NULL, NULL);
1401 	}
1402 #endif
1403 }
1404 
1405 void
1406 slhci_poll(struct usbd_bus *bus) /* XXX necessary? */
1407 {
1408 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1409 	struct slhci_softc *sc;
1410 
1411 	sc = SLHCI_BUS2SC(bus);
1412 
1413 	DLOG(D_TRACE, "slhci_poll", 0,0,0,0);
1414 
1415 	slhci_lock_call(sc, &slhci_do_poll, NULL, NULL);
1416 }
1417 
1418 void
1419 slhci_done(struct usbd_xfer *xfer)
1420 {
1421 }
1422 
1423 void
1424 slhci_void(void *v) {}
1425 
1426 /* End out of lock functions. Start lock entry functions. */
1427 
1428 #ifdef SLHCI_MEM_ACCOUNTING
1429 void
1430 slhci_mem_use(struct usbd_bus *bus, int val)
1431 {
1432 	struct slhci_softc *sc = SLHCI_BUS2SC(bus);
1433 
1434 	mutex_enter(&sc->sc_intr_lock);
1435 	sc->sc_mem_use += val;
1436 	mutex_exit(&sc->sc_intr_lock);
1437 }
1438 #endif
1439 
1440 void
1441 slhci_reset_entry(void *arg)
1442 {
1443 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1444 	struct slhci_softc *sc = arg;
1445 
1446 	mutex_enter(&sc->sc_intr_lock);
1447 	slhci_reset(sc);
1448 	/*
1449 	 * We cannot call the callback directly since we could then be reset
1450 	 * again before finishing and need the callout delay for timing.
1451 	 * Scheduling the callout again before we exit would defeat the reap
1452 	 * mechanism since we could be unlocked while the reset flag is not
1453 	 * set. The callback code will check the wait queue.
1454 	 */
1455 	slhci_callback_schedule(sc);
1456 	mutex_exit(&sc->sc_intr_lock);
1457 }
1458 
1459 usbd_status
1460 slhci_lock_call(struct slhci_softc *sc, LockCallFunc lcf, struct slhci_pipe
1461     *spipe, struct usbd_xfer *xfer)
1462 {
1463 	usbd_status ret;
1464 
1465 	mutex_enter(&sc->sc_intr_lock);
1466 	ret = (*lcf)(sc, spipe, xfer);
1467 	slhci_main(sc);
1468 	mutex_exit(&sc->sc_intr_lock);
1469 
1470 	return ret;
1471 }
1472 
1473 void
1474 slhci_start_entry(struct slhci_softc *sc, struct slhci_pipe *spipe)
1475 {
1476 	struct slhci_transfers *t;
1477 
1478 	mutex_enter(&sc->sc_intr_lock);
1479 	t = &sc->sc_transfers;
1480 
1481 	if (!(t->flags & (F_AINPROG|F_BINPROG))) {
1482 		slhci_enter_xfer(sc, spipe);
1483 		slhci_dotransfer(sc);
1484 		slhci_main(sc);
1485 	} else {
1486 		enter_waitq(sc, spipe);
1487 	}
1488 	mutex_exit(&sc->sc_intr_lock);
1489 }
1490 
1491 void
1492 slhci_callback_entry(void *arg)
1493 {
1494 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1495 	struct slhci_softc *sc;
1496 	struct slhci_transfers *t;
1497 
1498 	sc = (struct slhci_softc *)arg;
1499 
1500 	mutex_enter(&sc->sc_intr_lock);
1501 	t = &sc->sc_transfers;
1502 	DLOG(D_SOFT, "callback_entry flags %#jx", t->flags, 0,0,0);
1503 
1504 repeat:
1505 	slhci_callback(sc);
1506 
1507 	if (!gcq_empty(&sc->sc_waitq)) {
1508 		slhci_enter_xfers(sc);
1509 		slhci_dotransfer(sc);
1510 		slhci_waitintr(sc, 0);
1511 		goto repeat;
1512 	}
1513 
1514 	t->flags &= ~F_CALLBACK;
1515 	mutex_exit(&sc->sc_intr_lock);
1516 }
1517 
1518 void
1519 slhci_do_callback(struct slhci_softc *sc, struct usbd_xfer *xfer)
1520 {
1521 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1522 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1523 
1524 	start_cc_time(&t_callback, (u_int)xfer);
1525 	mutex_exit(&sc->sc_intr_lock);
1526 
1527 	mutex_enter(&sc->sc_lock);
1528 	usb_transfer_complete(xfer);
1529 	mutex_exit(&sc->sc_lock);
1530 
1531 	mutex_enter(&sc->sc_intr_lock);
1532 	stop_cc_time(&t_callback);
1533 }
1534 
1535 int
1536 slhci_intr(void *arg)
1537 {
1538 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1539 	struct slhci_softc *sc = arg;
1540 	int ret = 0;
1541 	int irq;
1542 
1543 	start_cc_time(&t_hard_int, (unsigned int)arg);
1544 	mutex_enter(&sc->sc_intr_lock);
1545 
1546 	do {
1547 		irq = slhci_dointr(sc);
1548 		ret |= irq;
1549 		slhci_main(sc);
1550 	} while (irq);
1551 	mutex_exit(&sc->sc_intr_lock);
1552 
1553 	stop_cc_time(&t_hard_int);
1554 	return ret;
1555 }
1556 
1557 /* called with interrupt lock only held. */
1558 void
1559 slhci_main(struct slhci_softc *sc)
1560 {
1561 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1562 	struct slhci_transfers *t;
1563 
1564 	t = &sc->sc_transfers;
1565 
1566 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1567 
1568 waitcheck:
1569 	slhci_waitintr(sc, slhci_wait_time);
1570 
1571 	/*
1572 	 * The direct call is needed in the ub_usepolling and disabled cases
1573 	 * since the soft interrupt is not available.  In the disabled case,
1574 	 * this code can be reached from the usb detach, after the reaping of
1575 	 * the soft interrupt.  That test could be !F_ACTIVE, but there is no
1576 	 * reason not to make the callbacks directly in the other DISABLED
1577 	 * cases.
1578 	 */
1579 	if ((t->flags & F_ROOTINTR) || !gcq_empty(&t->q[Q_CALLBACKS])) {
1580 		if (__predict_false(sc->sc_bus.ub_usepolling ||
1581 		    t->flags & F_DISABLED))
1582 			slhci_callback(sc);
1583 		else
1584 			slhci_callback_schedule(sc);
1585 	}
1586 
1587 	if (!gcq_empty(&sc->sc_waitq)) {
1588 		slhci_enter_xfers(sc);
1589 		slhci_dotransfer(sc);
1590 		goto waitcheck;
1591 	}
1592 	DLOG(D_INTR, "... done", 0, 0, 0, 0);
1593 }
1594 
1595 /* End lock entry functions. Start in lock function. */
1596 
1597 /* Register read/write routines and barriers. */
1598 #ifdef SLHCI_BUS_SPACE_BARRIERS
1599 #define BSB(a, b, c, d, e) bus_space_barrier(a, b, c, d, BUS_SPACE_BARRIER_ # e)
1600 #define BSB_SYNC(a, b, c, d) bus_space_barrier(a, b, c, d, BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE)
1601 #else /* now !SLHCI_BUS_SPACE_BARRIERS */
1602 #define BSB(a, b, c, d, e) __USE(d)
1603 #define BSB_SYNC(a, b, c, d)
1604 #endif /* SLHCI_BUS_SPACE_BARRIERS */
1605 
1606 static void
1607 slhci_write(struct slhci_softc *sc, uint8_t addr, uint8_t data)
1608 {
1609 	bus_size_t paddr, pdata, pst, psz;
1610 	bus_space_tag_t iot;
1611 	bus_space_handle_t ioh;
1612 
1613 	paddr = pst = 0;
1614 	pdata = sc->sc_stride;
1615 	psz = pdata * 2;
1616 	iot = sc->sc_iot;
1617 	ioh = sc->sc_ioh;
1618 
1619 	bus_space_write_1(iot, ioh, paddr, addr);
1620 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
1621 	bus_space_write_1(iot, ioh, pdata, data);
1622 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
1623 }
1624 
1625 static uint8_t
1626 slhci_read(struct slhci_softc *sc, uint8_t addr)
1627 {
1628 	bus_size_t paddr, pdata, pst, psz;
1629 	bus_space_tag_t iot;
1630 	bus_space_handle_t ioh;
1631 	uint8_t data;
1632 
1633 	paddr = pst = 0;
1634 	pdata = sc->sc_stride;
1635 	psz = pdata * 2;
1636 	iot = sc->sc_iot;
1637 	ioh = sc->sc_ioh;
1638 
1639 	bus_space_write_1(iot, ioh, paddr, addr);
1640 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_READ);
1641 	data = bus_space_read_1(iot, ioh, pdata);
1642 	BSB(iot, ioh, pst, psz, READ_BEFORE_WRITE);
1643 	return data;
1644 }
1645 
1646 #if 0 /* auto-increment mode broken, see errata doc */
1647 static void
1648 slhci_write_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
1649 {
1650 	bus_size_t paddr, pdata, pst, psz;
1651 	bus_space_tag_t iot;
1652 	bus_space_handle_t ioh;
1653 
1654 	paddr = pst = 0;
1655 	pdata = sc->sc_stride;
1656 	psz = pdata * 2;
1657 	iot = sc->sc_iot;
1658 	ioh = sc->sc_ioh;
1659 
1660 	bus_space_write_1(iot, ioh, paddr, addr);
1661 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
1662 	bus_space_write_multi_1(iot, ioh, pdata, buf, l);
1663 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
1664 }
1665 
1666 static void
1667 slhci_read_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
1668 {
1669 	bus_size_t paddr, pdata, pst, psz;
1670 	bus_space_tag_t iot;
1671 	bus_space_handle_t ioh;
1672 
1673 	paddr = pst = 0;
1674 	pdata = sc->sc_stride;
1675 	psz = pdata * 2;
1676 	iot = sc->sc_iot;
1677 	ioh = sc->sc_ioh;
1678 
1679 	bus_space_write_1(iot, ioh, paddr, addr);
1680 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_READ);
1681 	bus_space_read_multi_1(iot, ioh, pdata, buf, l);
1682 	BSB(iot, ioh, pst, psz, READ_BEFORE_WRITE);
1683 }
1684 #else
1685 static void
1686 slhci_write_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
1687 {
1688 #if 1
1689 	for (; l; addr++, buf++, l--)
1690 		slhci_write(sc, addr, *buf);
1691 #else
1692 	bus_size_t paddr, pdata, pst, psz;
1693 	bus_space_tag_t iot;
1694 	bus_space_handle_t ioh;
1695 
1696 	paddr = pst = 0;
1697 	pdata = sc->sc_stride;
1698 	psz = pdata * 2;
1699 	iot = sc->sc_iot;
1700 	ioh = sc->sc_ioh;
1701 
1702 	for (; l; addr++, buf++, l--) {
1703 		bus_space_write_1(iot, ioh, paddr, addr);
1704 		BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
1705 		bus_space_write_1(iot, ioh, pdata, *buf);
1706 		BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
1707 	}
1708 #endif
1709 }
1710 
1711 static void
1712 slhci_read_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
1713 {
1714 #if 1
1715 	for (; l; addr++, buf++, l--)
1716 		*buf = slhci_read(sc, addr);
1717 #else
1718 	bus_size_t paddr, pdata, pst, psz;
1719 	bus_space_tag_t iot;
1720 	bus_space_handle_t ioh;
1721 
1722 	paddr = pst = 0;
1723 	pdata = sc->sc_stride;
1724 	psz = pdata * 2;
1725 	iot = sc->sc_iot;
1726 	ioh = sc->sc_ioh;
1727 
1728 	for (; l; addr++, buf++, l--) {
1729 		bus_space_write_1(iot, ioh, paddr, addr);
1730 		BSB(iot, ioh, pst, psz, WRITE_BEFORE_READ);
1731 		*buf = bus_space_read_1(iot, ioh, pdata);
1732 		BSB(iot, ioh, pst, psz, READ_BEFORE_WRITE);
1733 	}
1734 #endif
1735 }
1736 #endif
1737 
1738 /*
1739  * After calling waitintr it is necessary to either call slhci_callback or
1740  * schedule the callback if necessary.  The callback cannot be called directly
1741  * from the hard interrupt since it interrupts at a high IPL and callbacks
1742  * can do copyout and such.
1743  */
1744 static void
1745 slhci_waitintr(struct slhci_softc *sc, int wait_time)
1746 {
1747 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1748 	struct slhci_transfers *t;
1749 
1750 	t = &sc->sc_transfers;
1751 
1752 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1753 
1754 	if (__predict_false(sc->sc_bus.ub_usepolling))
1755 		wait_time = 12000;
1756 
1757 	while (t->pend <= wait_time) {
1758 		DLOG(D_WAIT, "waiting... frame %jd pend %jd flags %#jx",
1759 		    t->frame, t->pend, t->flags, 0);
1760 		LK_SLASSERT(t->flags & F_ACTIVE, sc, NULL, NULL, return);
1761 		LK_SLASSERT(t->flags & (F_AINPROG|F_BINPROG), sc, NULL, NULL,
1762 		    return);
1763 		slhci_dointr(sc);
1764 	}
1765 	DLOG(D_WAIT, "... done", 0, 0, 0, 0);
1766 }
1767 
1768 static int
1769 slhci_dointr(struct slhci_softc *sc)
1770 {
1771 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1772 	struct slhci_transfers *t;
1773 	struct slhci_pipe *tosp;
1774 	uint8_t r;
1775 
1776 	t = &sc->sc_transfers;
1777 
1778 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1779 
1780 	if (sc->sc_ier == 0) {
1781 		DLOG(D_INTR, "sc_ier is zero", 0, 0, 0, 0);
1782 		return 0;
1783 	}
1784 
1785 	r = slhci_read(sc, SL11_ISR);
1786 
1787 #ifdef SLHCI_DEBUG
1788 	if (slhcidebug & SLHCI_D_INTR && r & sc->sc_ier &&
1789 	    ((r & ~(SL11_ISR_SOF|SL11_ISR_DATA)) || slhcidebug & SLHCI_D_SOF)) {
1790 		uint8_t e, f;
1791 
1792 		e = slhci_read(sc, SL11_IER);
1793 		f = slhci_read(sc, SL11_CTRL);
1794 		DDOLOG("Flags=%#x IER=%#x ISR=%#x CTRL=%#x", t->flags, e, r, f);
1795 		DDOLOGCTRL(f);
1796 		DDOLOGISR(r);
1797 	}
1798 #endif
1799 
1800 	/*
1801 	 * check IER for corruption occasionally.  Assume that the above
1802 	 * sc_ier == 0 case works correctly.
1803 	 */
1804 	if (__predict_false(sc->sc_ier_check++ > SLHCI_IER_CHECK_FREQUENCY)) {
1805 		sc->sc_ier_check = 0;
1806 		if (sc->sc_ier != slhci_read(sc, SL11_IER)) {
1807 			printf("%s: IER value corrupted! halted\n",
1808 			    SC_NAME(sc));
1809 			DDOLOG("IER value corrupted! halted", 0, 0, 0, 0);
1810 			slhci_halt(sc, NULL, NULL);
1811 			return 1;
1812 		}
1813 	}
1814 
1815 	r &= sc->sc_ier;
1816 
1817 	if (r == 0) {
1818 		DLOG(D_INTR, "r is zero", 0, 0, 0, 0);
1819 		return 0;
1820 	}
1821 
1822 	sc->sc_ier_check = 0;
1823 
1824 	slhci_write(sc, SL11_ISR, r);
1825 	BSB_SYNC(sc->iot, sc->ioh, sc->pst, sc->psz);
1826 
1827 	/* If we have an insertion event we do not care about anything else. */
1828 	if (__predict_false(r & SL11_ISR_INSERT)) {
1829 		slhci_insert(sc);
1830 		DLOG(D_INTR, "... done", 0, 0, 0, 0);
1831 		return 1;
1832 	}
1833 
1834 	stop_cc_time(&t_intr);
1835 	start_cc_time(&t_intr, r);
1836 
1837 	if (r & SL11_ISR_SOF) {
1838 		t->frame++;
1839 
1840 		gcq_merge_tail(&t->q[Q_CB], &t->q[Q_NEXT_CB]);
1841 
1842 		/*
1843 		 * SOFCHECK flags are cleared in tstart.  Two flags are needed
1844 		 * since the first SOF interrupt processed after the transfer
1845 		 * is started might have been generated before the transfer
1846 		 * was started.
1847 		 */
1848 		if (__predict_false(t->flags & F_SOFCHECK2 && t->flags &
1849 		    (F_AINPROG|F_BINPROG))) {
1850 			printf("%s: Missed transfer completion. halted\n",
1851 			    SC_NAME(sc));
1852 			DDOLOG("Missed transfer completion. halted", 0, 0, 0,
1853 			    0);
1854 			slhci_halt(sc, NULL, NULL);
1855 			return 1;
1856 		} else if (t->flags & F_SOFCHECK1) {
1857 			t->flags |= F_SOFCHECK2;
1858 		} else
1859 			t->flags |= F_SOFCHECK1;
1860 
1861 		if (t->flags & F_CHANGE)
1862 			t->flags |= F_ROOTINTR;
1863 
1864 		while (__predict_true(GOT_FIRST_TO(tosp, t)) &&
1865 		    __predict_false(tosp->to_frame <= t->frame)) {
1866 			tosp->xfer->ux_status = USBD_TIMEOUT;
1867 			slhci_do_abort(sc, tosp, tosp->xfer);
1868 			enter_callback(t, tosp);
1869 		}
1870 
1871 		/*
1872 		 * Start any waiting transfers right away.  If none, we will
1873 		 * start any new transfers later.
1874 		 */
1875 		slhci_tstart(sc);
1876 	}
1877 
1878 	if (r & (SL11_ISR_USBA|SL11_ISR_USBB)) {
1879 		int ab;
1880 
1881 		if ((r & (SL11_ISR_USBA|SL11_ISR_USBB)) ==
1882 		    (SL11_ISR_USBA|SL11_ISR_USBB)) {
1883 			if (!(t->flags & (F_AINPROG|F_BINPROG)))
1884 				return 1; /* presume card pulled */
1885 
1886 			LK_SLASSERT((t->flags & (F_AINPROG|F_BINPROG)) !=
1887 			    (F_AINPROG|F_BINPROG), sc, NULL, NULL, return 1);
1888 
1889 			/*
1890 			 * This should never happen (unless card removal just
1891 			 * occurred) but appeared frequently when both
1892 			 * transfers were started at the same time and was
1893 			 * accompanied by data corruption.  It still happens
1894 			 * at times.  I have not seen data correption except
1895 			 * when the STATUS bit gets set, which now causes the
1896 			 * driver to halt, however this should still not
1897 			 * happen so the warning is kept.  See comment in
1898 			 * abdone, below.
1899 			 */
1900 			printf("%s: Transfer reported done but not started! "
1901 			    "Verify data integrity if not detaching. "
1902 			    " flags %#x r %x\n", SC_NAME(sc), t->flags, r);
1903 
1904 			if (!(t->flags & F_AINPROG))
1905 				r &= ~SL11_ISR_USBA;
1906 			else
1907 				r &= ~SL11_ISR_USBB;
1908 		}
1909 		t->pend = INT_MAX;
1910 
1911 		if (r & SL11_ISR_USBA)
1912 			ab = A;
1913 		else
1914 			ab = B;
1915 
1916 		/*
1917 		 * This happens when a low speed device is attached to
1918 		 * a hub with chip rev 1.5.  SOF stops, but a few transfers
1919 		 * still work before causing this error.
1920 		 */
1921 		if (!(t->flags & (ab ? F_BINPROG : F_AINPROG))) {
1922 			printf("%s: %s done but not in progress! halted\n",
1923 			    SC_NAME(sc), ab ? "B" : "A");
1924 			DDOLOG("AB=%d done but not in progress! halted", ab,
1925 			    0, 0, 0);
1926 			slhci_halt(sc, NULL, NULL);
1927 			return 1;
1928 		}
1929 
1930 		t->flags &= ~(ab ? F_BINPROG : F_AINPROG);
1931 		slhci_tstart(sc);
1932 		stop_cc_time(&t_ab[ab]);
1933 		start_cc_time(&t_abdone, t->flags);
1934 		slhci_abdone(sc, ab);
1935 		stop_cc_time(&t_abdone);
1936 	}
1937 
1938 	slhci_dotransfer(sc);
1939 
1940 	DLOG(D_INTR, "... done", 0, 0, 0, 0);
1941 
1942 	return 1;
1943 }
1944 
1945 static void
1946 slhci_abdone(struct slhci_softc *sc, int ab)
1947 {
1948 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
1949 	struct slhci_transfers *t;
1950 	struct slhci_pipe *spipe;
1951 	struct usbd_xfer *xfer;
1952 	uint8_t status, buf_start;
1953 	uint8_t *target_buf;
1954 	unsigned int actlen;
1955 	int head;
1956 
1957 	t = &sc->sc_transfers;
1958 
1959 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1960 
1961 	DLOG(D_TRACE, "ABDONE flags %#jx", t->flags, 0,0,0);
1962 
1963 	DLOG(D_MSG, "DONE AB=%jd spipe %#jx len %jd xfer %#jx", ab,
1964 	    t->spipe[ab], (uintptr_t)t->len[ab],
1965 	    (uintptr_t)(t->spipe[ab] ? t->spipe[ab]->xfer : NULL));
1966 
1967 	spipe = t->spipe[ab];
1968 
1969 	/*
1970 	 * skip this one if aborted; do not call return from the rest of the
1971 	 * function unless halting, else t->len will not be cleared.
1972 	 */
1973 	if (spipe == NULL)
1974 		goto done;
1975 
1976 	t->spipe[ab] = NULL;
1977 
1978 	xfer = spipe->xfer;
1979 
1980 	gcq_remove(&spipe->to);
1981 
1982 	LK_SLASSERT(xfer != NULL, sc, spipe, NULL, return);
1983 
1984 	status = slhci_read(sc, slhci_tregs[ab][STAT]);
1985 
1986 	/*
1987 	 * I saw no status or remaining length greater than the requested
1988 	 * length in early driver versions in circumstances I assumed caused
1989 	 * excess power draw.  I am no longer able to reproduce this when
1990 	 * causing excess power draw circumstances.
1991 	 *
1992 	 * Disabling a power check and attaching aue to a keyboard and hub
1993 	 * that is directly attached (to CFU1U, 100mA max, aue 160mA, keyboard
1994 	 * 98mA) sometimes works and sometimes fails to configure.  After
1995 	 * removing the aue and attaching a self-powered umass dvd reader
1996 	 * (unknown if it draws power from the host also) soon a single Error
1997 	 * status occurs then only timeouts. The controller soon halts freeing
1998 	 * memory due to being ONQU instead of BUSY.  This may be the same
1999 	 * basic sequence that caused the no status/bad length errors.  The
2000 	 * umass device seems to work (better at least) with the keyboard hub
2001 	 * when not first attaching aue (tested once reading an approximately
2002 	 * 200MB file).
2003 	 *
2004 	 * Overflow can indicate that the device and host disagree about how
2005 	 * much data has been transfered.  This may indicate a problem at any
2006 	 * point during the transfer, not just when the error occurs.  It may
2007 	 * indicate data corruption.  A warning message is printed.
2008 	 *
2009 	 * Trying to use both A and B transfers at the same time results in
2010 	 * incorrect transfer completion ISR reports and the status will then
2011 	 * include SL11_EPSTAT_SETUP, which is apparently set while the
2012 	 * transfer is in progress.  I also noticed data corruption, even
2013 	 * after waiting for the transfer to complete. The driver now avoids
2014 	 * trying to start both at the same time.
2015 	 *
2016 	 * I had accidently initialized the B registers before they were valid
2017 	 * in some driver versions.  Since every other performance enhancing
2018 	 * feature has been confirmed buggy in the errata doc, I have not
2019 	 * tried both transfers at once again with the documented
2020 	 * initialization order.
2021 	 *
2022 	 * However, I have seen this problem again ("done but not started"
2023 	 * errors), which in some cases cases the SETUP status bit to remain
2024 	 * set on future transfers.  In other cases, the SETUP bit is not set
2025 	 * and no data corruption occurs.  This occured while using both umass
2026 	 * and aue on a powered hub (maybe triggered by some local activity
2027 	 * also) and needs several reads of the 200MB file to trigger.  The
2028 	 * driver now halts if SETUP is detected.
2029  	 */
2030 
2031 	actlen = 0;
2032 
2033 	if (__predict_false(!status)) {
2034 		DDOLOG("no status! xfer %p spipe %p", xfer, spipe, 0,0);
2035 		printf("%s: no status! halted\n", SC_NAME(sc));
2036 		slhci_halt(sc, spipe, xfer);
2037 		return;
2038 	}
2039 
2040 #ifdef SLHCI_DEBUG
2041 	if ((slhcidebug & SLHCI_D_NAK) ||
2042 	    (status & SL11_EPSTAT_ERRBITS) != SL11_EPSTAT_NAK) {
2043 	    	DDOLOG("USB Status = %#.2x", status, 0, 0, 0);
2044 		DDOLOGSTATUS(status);
2045 	}
2046 #endif
2047 
2048 	if (!(status & SL11_EPSTAT_ERRBITS)) {
2049 		unsigned int cont = slhci_read(sc, slhci_tregs[ab][CONT]);
2050 		unsigned int len = spipe->tregs[LEN];
2051 		DLOG(D_XFER, "cont %jd len %jd", cont, len, 0, 0);
2052 		if ((status & SL11_EPSTAT_OVERFLOW) || cont > len) {
2053 			DDOLOG("overflow - cont %d len %d xfer->ux_length %d "
2054 			    "xfer->actlen %d", cont, len, xfer->ux_length,
2055 			    xfer->ux_actlen);
2056 			printf("%s: overflow cont %d len %d xfer->ux_length"
2057 			    " %d xfer->ux_actlen %d\n", SC_NAME(sc), cont,
2058 			    len, xfer->ux_length, xfer->ux_actlen);
2059 			actlen = len;
2060 		} else {
2061 			actlen = len - cont;
2062 		}
2063 		spipe->nerrs = 0;
2064 	}
2065 
2066 	/* Actual copyin done after starting next transfer. */
2067 	if (actlen && (spipe->tregs[PID] & SL11_PID_BITS) == SL11_PID_IN) {
2068 		target_buf = spipe->buffer;
2069 		buf_start = spipe->tregs[ADR];
2070 	} else {
2071 		target_buf = NULL;
2072 		buf_start = 0; /* XXX gcc uninitialized warnings */
2073 	}
2074 
2075 	if (status & SL11_EPSTAT_ERRBITS) {
2076 		status &= SL11_EPSTAT_ERRBITS;
2077 		if (status & SL11_EPSTAT_SETUP) {
2078 			printf("%s: Invalid controller state detected! "
2079 			    "halted\n", SC_NAME(sc));
2080 			DDOLOG("Invalid controller state detected! "
2081 			    "halted", 0, 0, 0, 0);
2082 			slhci_halt(sc, spipe, xfer);
2083 			return;
2084 		} else if (__predict_false(sc->sc_bus.ub_usepolling)) {
2085 			head = Q_CALLBACKS;
2086 			if (status & SL11_EPSTAT_STALL)
2087 				xfer->ux_status = USBD_STALLED;
2088 			else if (status & SL11_EPSTAT_TIMEOUT)
2089 				xfer->ux_status = USBD_TIMEOUT;
2090 			else if (status & SL11_EPSTAT_NAK)
2091 				head = Q_NEXT_CB;
2092 			else
2093 				xfer->ux_status = USBD_IOERROR;
2094 		} else if (status & SL11_EPSTAT_NAK) {
2095 			int i = spipe->pipe.up_interval;
2096 			if (i == 0)
2097 				i = 1;
2098 			DDOLOG("xfer %p spipe %p NAK delay by %d", xfer, spipe,
2099 			    i, 0);
2100 			spipe->lastframe = spipe->frame = t->frame + i;
2101 			slhci_queue_timed(sc, spipe);
2102 			goto queued;
2103 		} else if (++spipe->nerrs > SLHCI_MAX_RETRIES ||
2104 		    (status & SL11_EPSTAT_STALL)) {
2105 			DDOLOG("xfer %p spipe %p nerrs %d", xfer, spipe,
2106 			    spipe->nerrs, 0);
2107 			if (status & SL11_EPSTAT_STALL)
2108 				xfer->ux_status = USBD_STALLED;
2109 			else if (status & SL11_EPSTAT_TIMEOUT)
2110 				xfer->ux_status = USBD_TIMEOUT;
2111 			else
2112 				xfer->ux_status = USBD_IOERROR;
2113 
2114 			DLOG(D_ERR, "Max retries reached! status %#jx "
2115 			    "xfer->ux_status %jd", status, xfer->ux_status, 0,
2116 			    0);
2117 			DDOLOGSTATUS(status);
2118 
2119 			head = Q_CALLBACKS;
2120 		} else {
2121 			head = Q_NEXT_CB;
2122 		}
2123 	} else if (spipe->ptype == PT_CTRL_SETUP) {
2124 		spipe->tregs[PID] = spipe->newpid;
2125 
2126 		if (xfer->ux_length) {
2127 			LK_SLASSERT(spipe->newlen[1] != 0, sc, spipe, xfer,
2128 			    return);
2129 			spipe->tregs[LEN] = spipe->newlen[1];
2130 			spipe->bustime = spipe->newbustime[1];
2131 			spipe->buffer = xfer->ux_buf;
2132 			spipe->ptype = PT_CTRL_DATA;
2133 		} else {
2134 status_setup:
2135 			/* CTRL_DATA swaps direction in PID then jumps here */
2136 			spipe->tregs[LEN] = 0;
2137 			if (spipe->pflags & PF_LS)
2138 				spipe->bustime = SLHCI_LS_CONST;
2139 			else
2140 				spipe->bustime = SLHCI_FS_CONST;
2141 			spipe->ptype = PT_CTRL_STATUS;
2142 			spipe->buffer = NULL;
2143 		}
2144 
2145 		/* Status or first data packet must be DATA1. */
2146 		spipe->control |= SL11_EPCTRL_DATATOGGLE;
2147 		if ((spipe->tregs[PID] & SL11_PID_BITS) == SL11_PID_IN)
2148 			spipe->control &= ~SL11_EPCTRL_DIRECTION;
2149 		else
2150 			spipe->control |= SL11_EPCTRL_DIRECTION;
2151 
2152 		head = Q_CB;
2153 	} else if (spipe->ptype == PT_CTRL_STATUS) {
2154 		head = Q_CALLBACKS;
2155 	} else { /* bulk, intr, control data */
2156 		xfer->ux_actlen += actlen;
2157 		spipe->control ^= SL11_EPCTRL_DATATOGGLE;
2158 
2159 		if (actlen == spipe->tregs[LEN] &&
2160 		    (xfer->ux_length > xfer->ux_actlen || spipe->wantshort)) {
2161 			spipe->buffer += actlen;
2162 			LK_SLASSERT(xfer->ux_length >= xfer->ux_actlen, sc,
2163 			    spipe, xfer, return);
2164 			if (xfer->ux_length - xfer->ux_actlen < actlen) {
2165 				spipe->wantshort = 0;
2166 				spipe->tregs[LEN] = spipe->newlen[0];
2167 				spipe->bustime = spipe->newbustime[0];
2168 				LK_SLASSERT(xfer->ux_actlen +
2169 				    spipe->tregs[LEN] == xfer->ux_length, sc,
2170 				    spipe, xfer, return);
2171 			}
2172 			head = Q_CB;
2173 		} else if (spipe->ptype == PT_CTRL_DATA) {
2174 			spipe->tregs[PID] ^= SLHCI_PID_SWAP_IN_OUT;
2175 			goto status_setup;
2176 		} else {
2177 			if (spipe->ptype == PT_INTR) {
2178 				spipe->lastframe +=
2179 				    spipe->pipe.up_interval;
2180 				/*
2181 				 * If ack, we try to keep the
2182 				 * interrupt rate by using lastframe
2183 				 * instead of the current frame.
2184 				 */
2185 				spipe->frame = spipe->lastframe +
2186 				    spipe->pipe.up_interval;
2187 			}
2188 
2189 			/*
2190 			 * Set the toggle for the next transfer.  It
2191 			 * has already been toggled above, so the
2192 			 * current setting will apply to the next
2193 			 * transfer.
2194 			 */
2195 			if (spipe->control & SL11_EPCTRL_DATATOGGLE)
2196 				spipe->pflags |= PF_TOGGLE;
2197 			else
2198 				spipe->pflags &= ~PF_TOGGLE;
2199 
2200 			head = Q_CALLBACKS;
2201 		}
2202 	}
2203 
2204 	if (head == Q_CALLBACKS) {
2205 		gcq_remove(&spipe->to);
2206 
2207 	 	if (xfer->ux_status == USBD_IN_PROGRESS) {
2208 			LK_SLASSERT(xfer->ux_actlen <= xfer->ux_length, sc,
2209 			    spipe, xfer, return);
2210 			xfer->ux_status = USBD_NORMAL_COMPLETION;
2211 		}
2212 	}
2213 
2214 	enter_q(t, spipe, head);
2215 
2216 queued:
2217 	if (target_buf != NULL) {
2218 		slhci_dotransfer(sc);
2219 		start_cc_time(&t_copy_from_dev, actlen);
2220 		slhci_read_multi(sc, buf_start, target_buf, actlen);
2221 		stop_cc_time(&t_copy_from_dev);
2222 		DLOGBUF(D_BUF, target_buf, actlen);
2223 		t->pend -= SLHCI_FS_CONST + SLHCI_FS_DATA_TIME(actlen);
2224 	}
2225 
2226 done:
2227 	t->len[ab] = -1;
2228 }
2229 
2230 static void
2231 slhci_tstart(struct slhci_softc *sc)
2232 {
2233 	struct slhci_transfers *t;
2234 	struct slhci_pipe *spipe;
2235 	int remaining_bustime;
2236 
2237 	t = &sc->sc_transfers;
2238 
2239 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2240 
2241 	if (!(t->flags & (F_AREADY|F_BREADY)))
2242 		return;
2243 
2244 	if (t->flags & (F_AINPROG|F_BINPROG|F_DISABLED))
2245 		return;
2246 
2247 	/*
2248 	 * We have about 6 us to get from the bus time check to
2249 	 * starting the transfer or we might babble or the chip might fail to
2250 	 * signal transfer complete.  This leaves no time for any other
2251 	 * interrupts.
2252 	 */
2253 	remaining_bustime = (int)(slhci_read(sc, SL811_CSOF)) << 6;
2254 	remaining_bustime -= SLHCI_END_BUSTIME;
2255 
2256 	/*
2257 	 * Start one transfer only, clearing any aborted transfers that are
2258 	 * not yet in progress and skipping missed isoc. It is easier to copy
2259 	 * & paste most of the A/B sections than to make the logic work
2260 	 * otherwise and this allows better constant use.
2261 	 */
2262 	if (t->flags & F_AREADY) {
2263 		spipe = t->spipe[A];
2264 		if (spipe == NULL) {
2265 			t->flags &= ~F_AREADY;
2266 			t->len[A] = -1;
2267 		} else if (remaining_bustime >= spipe->bustime) {
2268 			t->flags &= ~(F_AREADY|F_SOFCHECK1|F_SOFCHECK2);
2269 			t->flags |= F_AINPROG;
2270 			start_cc_time(&t_ab[A], spipe->tregs[LEN]);
2271 			slhci_write(sc, SL11_E0CTRL, spipe->control);
2272 			goto pend;
2273 		}
2274 	}
2275 	if (t->flags & F_BREADY) {
2276 		spipe = t->spipe[B];
2277 		if (spipe == NULL) {
2278 			t->flags &= ~F_BREADY;
2279 			t->len[B] = -1;
2280 		} else if (remaining_bustime >= spipe->bustime) {
2281 			t->flags &= ~(F_BREADY|F_SOFCHECK1|F_SOFCHECK2);
2282 			t->flags |= F_BINPROG;
2283 			start_cc_time(&t_ab[B], spipe->tregs[LEN]);
2284 			slhci_write(sc, SL11_E1CTRL, spipe->control);
2285 pend:
2286 			t->pend = spipe->bustime;
2287 		}
2288 	}
2289 }
2290 
2291 static void
2292 slhci_dotransfer(struct slhci_softc *sc)
2293 {
2294 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2295 	struct slhci_transfers *t;
2296 	struct slhci_pipe *spipe;
2297 	int ab, i;
2298 
2299 	t = &sc->sc_transfers;
2300 
2301 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2302 
2303  	while ((t->len[A] == -1 || t->len[B] == -1) &&
2304 	    (GOT_FIRST_TIMED_COND(spipe, t, spipe->frame <= t->frame) ||
2305 	    GOT_FIRST_CB(spipe, t))) {
2306 		LK_SLASSERT(spipe->xfer != NULL, sc, spipe, NULL, return);
2307 		LK_SLASSERT(spipe->ptype != PT_ROOT_CTRL && spipe->ptype !=
2308 		    PT_ROOT_INTR, sc, spipe, NULL, return);
2309 
2310 		/* Check that this transfer can fit in the remaining memory. */
2311 		if (t->len[A] + t->len[B] + spipe->tregs[LEN] + 1 >
2312 		    SL11_MAX_PACKET_SIZE) {
2313 			DLOG(D_XFER, "Transfer does not fit. alen %jd blen %jd "
2314 			    "len %jd", t->len[A], t->len[B], spipe->tregs[LEN],
2315 			    0);
2316 			return;
2317 		}
2318 
2319 		gcq_remove(&spipe->xq);
2320 
2321 		if (t->len[A] == -1) {
2322 			ab = A;
2323 			spipe->tregs[ADR] = SL11_BUFFER_START;
2324 		} else {
2325 			ab = B;
2326 			spipe->tregs[ADR] = SL11_BUFFER_END -
2327 			    spipe->tregs[LEN];
2328 		}
2329 
2330 		t->len[ab] = spipe->tregs[LEN];
2331 
2332 		if (spipe->tregs[LEN] && (spipe->tregs[PID] & SL11_PID_BITS)
2333 		    != SL11_PID_IN) {
2334 			start_cc_time(&t_copy_to_dev,
2335 			    spipe->tregs[LEN]);
2336 			slhci_write_multi(sc, spipe->tregs[ADR],
2337 			    spipe->buffer, spipe->tregs[LEN]);
2338 			stop_cc_time(&t_copy_to_dev);
2339 			t->pend -= SLHCI_FS_CONST +
2340 			    SLHCI_FS_DATA_TIME(spipe->tregs[LEN]);
2341 		}
2342 
2343 		DLOG(D_MSG, "NEW TRANSFER AB=%jd flags %#jx alen %jd blen %jd",
2344 		    ab, t->flags, t->len[0], t->len[1]);
2345 
2346 		if (spipe->tregs[LEN])
2347 			i = 0;
2348 		else
2349 			i = 1;
2350 
2351 		for (; i <= 3; i++)
2352 			if (t->current_tregs[ab][i] != spipe->tregs[i]) {
2353 				t->current_tregs[ab][i] = spipe->tregs[i];
2354 				slhci_write(sc, slhci_tregs[ab][i],
2355 				    spipe->tregs[i]);
2356 			}
2357 
2358 		DLOG(D_SXFER, "Transfer len %jd pid %#jx dev %jd type %jd",
2359 		    spipe->tregs[LEN], spipe->tregs[PID], spipe->tregs[DEV],
2360 	    	    spipe->ptype);
2361 
2362 		t->spipe[ab] = spipe;
2363 		t->flags |= ab ? F_BREADY : F_AREADY;
2364 
2365 		slhci_tstart(sc);
2366 	}
2367 }
2368 
2369 /*
2370  * slhci_callback is called after the lock is taken.
2371  */
2372 static void
2373 slhci_callback(struct slhci_softc *sc)
2374 {
2375 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2376 	struct slhci_transfers *t;
2377 	struct slhci_pipe *spipe;
2378 	struct usbd_xfer *xfer;
2379 
2380 	t = &sc->sc_transfers;
2381 
2382 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2383 
2384 	DLOG(D_SOFT, "CB flags %#jx", t->flags, 0,0,0);
2385 	for (;;) {
2386 		if (__predict_false(t->flags & F_ROOTINTR)) {
2387 			t->flags &= ~F_ROOTINTR;
2388 			if (t->rootintr != NULL) {
2389 				u_char *p;
2390 
2391 				p = t->rootintr->ux_buf;
2392 				p[0] = 2;
2393 				t->rootintr->ux_actlen = 1;
2394 				t->rootintr->ux_status = USBD_NORMAL_COMPLETION;
2395 				xfer = t->rootintr;
2396 				goto do_callback;
2397 			}
2398 		}
2399 
2400 
2401 		if (!DEQUEUED_CALLBACK(spipe, t))
2402 			return;
2403 
2404 		xfer = spipe->xfer;
2405 		LK_SLASSERT(xfer != NULL, sc, spipe, NULL, return);
2406 		spipe->xfer = NULL;
2407 		DLOG(D_XFER, "xfer callback length %jd actlen %jd spipe %#jx "
2408 		    "type %jd", xfer->ux_length, (uintptr_t)xfer->ux_actlen,
2409 		    (uintptr_t)spipe, spipe->ptype);
2410 do_callback:
2411 		slhci_do_callback(sc, xfer);
2412 	}
2413 }
2414 
2415 static void
2416 slhci_enter_xfer(struct slhci_softc *sc, struct slhci_pipe *spipe)
2417 {
2418 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2419 	struct slhci_transfers *t;
2420 
2421 	t = &sc->sc_transfers;
2422 
2423 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2424 
2425 	if (__predict_false(t->flags & F_DISABLED) ||
2426 	    __predict_false(spipe->pflags & PF_GONE)) {
2427 		DLOG(D_MSG, "slhci_enter_xfer: DISABLED or GONE", 0,0,0,0);
2428 		spipe->xfer->ux_status = USBD_CANCELLED;
2429 	}
2430 
2431 	if (spipe->xfer->ux_status == USBD_IN_PROGRESS) {
2432 		if (spipe->xfer->ux_timeout) {
2433 			spipe->to_frame = t->frame + spipe->xfer->ux_timeout;
2434 			slhci_xfer_timer(sc, spipe);
2435 		}
2436 		if (spipe->pipe.up_interval)
2437 			slhci_queue_timed(sc, spipe);
2438 		else
2439 			enter_q(t, spipe, Q_CB);
2440 	} else
2441 		enter_callback(t, spipe);
2442 }
2443 
2444 static void
2445 slhci_enter_xfers(struct slhci_softc *sc)
2446 {
2447 	struct slhci_pipe *spipe;
2448 
2449 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2450 
2451 	while (DEQUEUED_WAITQ(spipe, sc))
2452 		slhci_enter_xfer(sc, spipe);
2453 }
2454 
2455 static void
2456 slhci_queue_timed(struct slhci_softc *sc, struct slhci_pipe *spipe)
2457 {
2458 	struct slhci_transfers *t;
2459 	struct gcq *q;
2460 	struct slhci_pipe *spp;
2461 
2462 	t = &sc->sc_transfers;
2463 
2464 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2465 
2466 	FIND_TIMED(q, t, spp, spp->frame > spipe->frame);
2467 	gcq_insert_before(q, &spipe->xq);
2468 }
2469 
2470 static void
2471 slhci_xfer_timer(struct slhci_softc *sc, struct slhci_pipe *spipe)
2472 {
2473 	struct slhci_transfers *t;
2474 	struct gcq *q;
2475 	struct slhci_pipe *spp;
2476 
2477 	t = &sc->sc_transfers;
2478 
2479 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2480 
2481 	FIND_TO(q, t, spp, spp->to_frame >= spipe->to_frame);
2482 	gcq_insert_before(q, &spipe->to);
2483 }
2484 
2485 static void
2486 slhci_callback_schedule(struct slhci_softc *sc)
2487 {
2488 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2489 	struct slhci_transfers *t;
2490 
2491 	t = &sc->sc_transfers;
2492 
2493 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2494 
2495 	if (t->flags & F_ACTIVE)
2496 		slhci_do_callback_schedule(sc);
2497 }
2498 
2499 static void
2500 slhci_do_callback_schedule(struct slhci_softc *sc)
2501 {
2502 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2503 	struct slhci_transfers *t;
2504 
2505 	t = &sc->sc_transfers;
2506 
2507 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2508 
2509 	DLOG(D_MSG, "flags %#jx", t->flags, 0, 0, 0);
2510 	if (!(t->flags & F_CALLBACK)) {
2511 		t->flags |= F_CALLBACK;
2512 		softint_schedule(sc->sc_cb_softintr);
2513 	}
2514 }
2515 
2516 #if 0
2517 /* must be called with lock taken. */
2518 /* XXX static */ void
2519 slhci_pollxfer(struct slhci_softc *sc, struct usbd_xfer *xfer)
2520 {
2521 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2522 	slhci_dotransfer(sc);
2523 	do {
2524 		slhci_dointr(sc);
2525 	} while (xfer->ux_status == USBD_IN_PROGRESS);
2526 	slhci_do_callback(sc, xfer);
2527 }
2528 #endif
2529 
2530 static usbd_status
2531 slhci_do_poll(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
2532     usbd_xfer *xfer)
2533 {
2534 	slhci_waitintr(sc, 0);
2535 
2536 	return USBD_NORMAL_COMPLETION;
2537 }
2538 
2539 static usbd_status
2540 slhci_lsvh_warn(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
2541     usbd_xfer *xfer)
2542 {
2543 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2544 	struct slhci_transfers *t;
2545 
2546 	t = &sc->sc_transfers;
2547 
2548 	if (!(t->flags & F_LSVH_WARNED)) {
2549 		printf("%s: Low speed device via hub disabled, "
2550 		    "see slhci(4)\n", SC_NAME(sc));
2551 		DDOLOG("Low speed device via hub disabled, "
2552 		    "see slhci(4)", SC_NAME(sc), 0,0,0);
2553 		t->flags |= F_LSVH_WARNED;
2554 	}
2555 	return USBD_INVAL;
2556 }
2557 
2558 static usbd_status
2559 slhci_isoc_warn(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
2560     usbd_xfer *xfer)
2561 {
2562 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2563 	struct slhci_transfers *t;
2564 
2565 	t = &sc->sc_transfers;
2566 
2567 	if (!(t->flags & F_ISOC_WARNED)) {
2568 		printf("%s: ISOC transfer not supported "
2569 		    "(see slhci(4))\n", SC_NAME(sc));
2570 		DDOLOG("ISOC transfer not supported "
2571 		    "(see slhci(4))", 0, 0, 0, 0);
2572 		t->flags |= F_ISOC_WARNED;
2573 	}
2574 	return USBD_INVAL;
2575 }
2576 
2577 static usbd_status
2578 slhci_open_pipe(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
2579     usbd_xfer *xfer)
2580 {
2581 	struct slhci_transfers *t;
2582 	struct usbd_pipe *pipe;
2583 
2584 	t = &sc->sc_transfers;
2585 	pipe = &spipe->pipe;
2586 
2587 	if (t->flags & F_DISABLED)
2588 		return USBD_CANCELLED;
2589 	else if (pipe->up_interval && !slhci_reserve_bustime(sc, spipe, 1))
2590 		return USBD_PENDING_REQUESTS;
2591 	else {
2592 		enter_all_pipes(t, spipe);
2593 		return USBD_NORMAL_COMPLETION;
2594 	}
2595 }
2596 
2597 static usbd_status
2598 slhci_close_pipe(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
2599     usbd_xfer *xfer)
2600 {
2601 	struct usbd_pipe *pipe;
2602 
2603 	pipe = &spipe->pipe;
2604 
2605 	if (pipe->up_interval && spipe->ptype != PT_ROOT_INTR)
2606 		slhci_reserve_bustime(sc, spipe, 0);
2607 	gcq_remove(&spipe->ap);
2608 	return USBD_NORMAL_COMPLETION;
2609 }
2610 
2611 static usbd_status
2612 slhci_do_abort(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
2613     usbd_xfer *xfer)
2614 {
2615 	struct slhci_transfers *t;
2616 
2617 	t = &sc->sc_transfers;
2618 
2619 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2620 
2621 	if (spipe->xfer == xfer) {
2622 		if (spipe->ptype == PT_ROOT_INTR) {
2623 			if (t->rootintr == spipe->xfer) /* XXX assert? */
2624 				t->rootintr = NULL;
2625 		} else {
2626 			gcq_remove(&spipe->to);
2627 			gcq_remove(&spipe->xq);
2628 
2629 			if (t->spipe[A] == spipe) {
2630 				t->spipe[A] = NULL;
2631 				if (!(t->flags & F_AINPROG))
2632 					t->len[A] = -1;
2633 			} else if (t->spipe[B] == spipe) {
2634 					t->spipe[B] = NULL;
2635 				if (!(t->flags & F_BINPROG))
2636 					t->len[B] = -1;
2637 			}
2638 		}
2639 
2640 		if (xfer->ux_status != USBD_TIMEOUT) {
2641 			spipe->xfer = NULL;
2642 			spipe->pipe.up_repeat = 0; /* XXX timeout? */
2643 		}
2644 	}
2645 
2646 	return USBD_NORMAL_COMPLETION;
2647 }
2648 
2649 /*
2650  * Called to deactivate or stop use of the controller instead of panicking.
2651  * Will cancel the xfer correctly even when not on a list.
2652  */
2653 static usbd_status
2654 slhci_halt(struct slhci_softc *sc, struct slhci_pipe *spipe,
2655     struct usbd_xfer *xfer)
2656 {
2657 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2658 	struct slhci_transfers *t;
2659 
2660 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2661 
2662 	t = &sc->sc_transfers;
2663 
2664 	DDOLOG("Halt! sc %p spipe %p xfer %p", sc, spipe, xfer, 0);
2665 
2666 	if (spipe != NULL)
2667 		slhci_log_spipe(spipe);
2668 
2669 	if (xfer != NULL)
2670 		slhci_log_xfer(xfer);
2671 
2672 	if (spipe != NULL && xfer != NULL && spipe->xfer == xfer &&
2673 	    !gcq_onlist(&spipe->xq) && t->spipe[A] != spipe && t->spipe[B] !=
2674 	    spipe) {
2675 		xfer->ux_status = USBD_CANCELLED;
2676 		enter_callback(t, spipe);
2677 	}
2678 
2679 	if (t->flags & F_ACTIVE) {
2680 		slhci_intrchange(sc, 0);
2681 		/*
2682 		 * leave power on when halting in case flash devices or disks
2683 		 * are attached, which may be writing and could be damaged
2684 		 * by abrupt power loss.  The root hub clear power feature
2685 		 * should still work after halting.
2686 		 */
2687 	}
2688 
2689 	t->flags &= ~F_ACTIVE;
2690 	t->flags |= F_UDISABLED;
2691 	if (!(t->flags & F_NODEV))
2692 		t->flags |= F_NODEV|F_CCONNECT|F_ROOTINTR;
2693 	slhci_drain(sc);
2694 
2695 	/* One last callback for the drain and device removal. */
2696 	slhci_do_callback_schedule(sc);
2697 
2698 	return USBD_NORMAL_COMPLETION;
2699 }
2700 
2701 /*
2702  * There are three interrupt states: no interrupts during reset and after
2703  * device deactivation, INSERT only for no device present but power on, and
2704  * SOF, INSERT, ADONE, and BDONE when device is present.
2705  */
2706 static void
2707 slhci_intrchange(struct slhci_softc *sc, uint8_t new_ier)
2708 {
2709 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2710 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2711 	if (sc->sc_ier != new_ier) {
2712 		DLOG(D_INTR, "New IER %#jx", new_ier, 0, 0, 0);
2713 		sc->sc_ier = new_ier;
2714 		slhci_write(sc, SL11_IER, new_ier);
2715 		BSB_SYNC(sc->iot, sc->ioh, sc->pst, sc->psz);
2716 	}
2717 }
2718 
2719 /*
2720  * Drain: cancel all pending transfers and put them on the callback list and
2721  * set the UDISABLED flag.  UDISABLED is cleared only by reset.
2722  */
2723 static void
2724 slhci_drain(struct slhci_softc *sc)
2725 {
2726 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2727 	struct slhci_transfers *t;
2728 	struct slhci_pipe *spipe;
2729 	struct gcq *q;
2730 	int i;
2731 
2732  	KASSERT(mutex_owned(&sc->sc_intr_lock));
2733 
2734 	t = &sc->sc_transfers;
2735 
2736 	DLOG(D_MSG, "DRAIN flags %#jx", t->flags, 0,0,0);
2737 
2738 	t->pend = INT_MAX;
2739 
2740 	for (i=0; i<=1; i++) {
2741 		t->len[i] = -1;
2742 		if (t->spipe[i] != NULL) {
2743 			enter_callback(t, t->spipe[i]);
2744 			t->spipe[i] = NULL;
2745 		}
2746 	}
2747 
2748 	/* Merge the queues into the callback queue. */
2749 	gcq_merge_tail(&t->q[Q_CALLBACKS], &t->q[Q_CB]);
2750 	gcq_merge_tail(&t->q[Q_CALLBACKS], &t->q[Q_NEXT_CB]);
2751 	gcq_merge_tail(&t->q[Q_CALLBACKS], &t->timed);
2752 
2753 	/*
2754 	 * Cancel all pipes.  Note that not all of these may be on the
2755 	 * callback queue yet; some could be in slhci_start, for example.
2756 	 */
2757 	FOREACH_AP(q, t, spipe) {
2758 		spipe->pflags |= PF_GONE;
2759 		spipe->pipe.up_repeat = 0;
2760 		spipe->pipe.up_aborting = 1;
2761 		if (spipe->xfer != NULL)
2762 			spipe->xfer->ux_status = USBD_CANCELLED;
2763 	}
2764 
2765 	gcq_remove_all(&t->to);
2766 
2767 	t->flags |= F_UDISABLED;
2768 	t->flags &= ~(F_AREADY|F_BREADY|F_AINPROG|F_BINPROG|F_LOWSPEED);
2769 }
2770 
2771 /*
2772  * RESET: SL11_CTRL_RESETENGINE=1 and SL11_CTRL_JKSTATE=0 for 50ms
2773  * reconfigure SOF after reset, must wait 2.5us before USB bus activity (SOF)
2774  * check attached device speed.
2775  * must wait 100ms before USB transaction according to app note, 10ms
2776  * by spec.  uhub does this delay
2777  *
2778  * Started from root hub set feature reset, which does step one.
2779  * ub_usepolling will call slhci_reset directly, otherwise the callout goes
2780  * through slhci_reset_entry.
2781  */
2782 void
2783 slhci_reset(struct slhci_softc *sc)
2784 {
2785 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2786 	struct slhci_transfers *t;
2787 	struct slhci_pipe *spipe;
2788 	struct gcq *q;
2789 	uint8_t r, pol, ctrl;
2790 
2791 	t = &sc->sc_transfers;
2792 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2793 
2794 	stop_cc_time(&t_delay);
2795 
2796 	KASSERT(t->flags & F_ACTIVE);
2797 
2798 	start_cc_time(&t_delay, 0);
2799 	stop_cc_time(&t_delay);
2800 
2801 	slhci_write(sc, SL11_CTRL, 0);
2802 	start_cc_time(&t_delay, 3);
2803 	DELAY(3);
2804 	stop_cc_time(&t_delay);
2805 	slhci_write(sc, SL11_ISR, 0xff);
2806 
2807 	r = slhci_read(sc, SL11_ISR);
2808 
2809 	if (r & SL11_ISR_INSERT)
2810 		slhci_write(sc, SL11_ISR, SL11_ISR_INSERT);
2811 
2812 	if (r & SL11_ISR_NODEV) {
2813 		DLOG(D_MSG, "NC", 0,0,0,0);
2814 		/*
2815 		 * Normally, the hard interrupt insert routine will issue
2816 		 * CCONNECT, however we need to do it here if the detach
2817 		 * happened during reset.
2818 		 */
2819 		if (!(t->flags & F_NODEV))
2820 			t->flags |= F_CCONNECT|F_ROOTINTR|F_NODEV;
2821 		slhci_intrchange(sc, SL11_IER_INSERT);
2822 	} else {
2823 		if (t->flags & F_NODEV)
2824 			t->flags |= F_CCONNECT;
2825 		t->flags &= ~(F_NODEV|F_LOWSPEED);
2826 		if (r & SL11_ISR_DATA) {
2827 			DLOG(D_MSG, "FS", 0,0,0,0);
2828 			pol = ctrl = 0;
2829 		} else {
2830 			DLOG(D_MSG, "LS", 0,0,0,0);
2831 			pol  = SL811_CSOF_POLARITY;
2832 			ctrl = SL11_CTRL_LOWSPEED;
2833 			t->flags |= F_LOWSPEED;
2834 		}
2835 
2836 		/* Enable SOF auto-generation */
2837 		t->frame = 0;	/* write to SL811_CSOF will reset frame */
2838 		slhci_write(sc, SL11_SOFTIME, 0xe0);
2839 		slhci_write(sc, SL811_CSOF, pol|SL811_CSOF_MASTER|0x2e);
2840 		slhci_write(sc, SL11_CTRL, ctrl|SL11_CTRL_ENABLESOF);
2841 
2842 		/*
2843 		 * According to the app note, ARM must be set
2844 		 * for SOF generation to work.  We initialize all
2845 		 * USBA registers here for current_tregs.
2846 		 */
2847 		slhci_write(sc, SL11_E0ADDR, SL11_BUFFER_START);
2848 		slhci_write(sc, SL11_E0LEN, 0);
2849 		slhci_write(sc, SL11_E0PID, SL11_PID_SOF);
2850 		slhci_write(sc, SL11_E0DEV, 0);
2851 		slhci_write(sc, SL11_E0CTRL, SL11_EPCTRL_ARM);
2852 
2853 		/*
2854 		 * Initialize B registers.  This can't be done earlier since
2855 		 * they are not valid until the SL811_CSOF register is written
2856 		 * above due to SL11H compatability.
2857 		 */
2858 		slhci_write(sc, SL11_E1ADDR, SL11_BUFFER_END - 8);
2859 		slhci_write(sc, SL11_E1LEN, 0);
2860 		slhci_write(sc, SL11_E1PID, 0);
2861 		slhci_write(sc, SL11_E1DEV, 0);
2862 
2863 		t->current_tregs[0][ADR] = SL11_BUFFER_START;
2864 		t->current_tregs[0][LEN] = 0;
2865 		t->current_tregs[0][PID] = SL11_PID_SOF;
2866 		t->current_tregs[0][DEV] = 0;
2867 		t->current_tregs[1][ADR] = SL11_BUFFER_END - 8;
2868 		t->current_tregs[1][LEN] = 0;
2869 		t->current_tregs[1][PID] = 0;
2870 		t->current_tregs[1][DEV] = 0;
2871 
2872 		/* SOF start will produce USBA interrupt */
2873 		t->len[A] = 0;
2874 		t->flags |= F_AINPROG;
2875 
2876 		slhci_intrchange(sc, SLHCI_NORMAL_INTERRUPTS);
2877 	}
2878 
2879 	t->flags &= ~(F_UDISABLED|F_RESET);
2880 	t->flags |= F_CRESET|F_ROOTINTR;
2881 	FOREACH_AP(q, t, spipe) {
2882 		spipe->pflags &= ~PF_GONE;
2883 		spipe->pipe.up_aborting = 0;
2884 	}
2885 	DLOG(D_MSG, "RESET done flags %#jx", t->flags, 0,0,0);
2886 }
2887 
2888 
2889 #ifdef SLHCI_DEBUG
2890 static int
2891 slhci_memtest(struct slhci_softc *sc)
2892 {
2893 	enum { ASC, DESC, EITHER = ASC };	/* direction */
2894 	enum { READ, WRITE };			/* operation */
2895 	const char *ptr, *elem;
2896 	size_t i;
2897 	const int low = SL11_BUFFER_START, high = SL11_BUFFER_END;
2898 	int addr = 0, dir = ASC, op = READ;
2899 	/* Extended March C- test algorithm (SOFs also) */
2900 	const char test[] = "E(w0) A(r0w1r1) A(r1w0r0) D(r0w1) D(r1w0) E(r0)";
2901 	char c;
2902 	const uint8_t dbs[] = { 0x00, 0x0f, 0x33, 0x55 }; /* data backgrounds */
2903 	uint8_t db;
2904 
2905 	/* Perform memory test for all data backgrounds. */
2906 	for (i = 0; i < __arraycount(dbs); i++) {
2907 		ptr = test;
2908 		elem = ptr;
2909 		/* Walk test algorithm string. */
2910 		while ((c = *ptr++) != '\0')
2911 			switch (tolower((int)c)) {
2912 			case 'a':
2913 				/* Address sequence is in ascending order. */
2914 				dir = ASC;
2915 				break;
2916 			case 'd':
2917 				/* Address sequence is in descending order. */
2918 				dir = DESC;
2919 				break;
2920 			case 'e':
2921 				/* Address sequence is in either order. */
2922 				dir = EITHER;
2923 				break;
2924 			case '(':
2925 				/* Start of test element (sequence). */
2926 				elem = ptr;
2927 				addr = (dir == ASC) ? low : high;
2928 				break;
2929 			case 'r':
2930 				/* read operation */
2931 				op = READ;
2932 				break;
2933 			case 'w':
2934 				/* write operation */
2935 				op = WRITE;
2936 				break;
2937 			case '0':
2938 			case '1':
2939 				/*
2940 				 * Execute previously set-up operation by
2941 				 * reading/writing non-inverted ('0') or
2942 				 * inverted ('1') data background.
2943 				 */
2944 				db = (c - '0') ? ~dbs[i] : dbs[i];
2945 				if (op == READ) {
2946 					if (slhci_read(sc, addr) != db)
2947 						return -1;
2948 				} else
2949 					slhci_write(sc, addr, db);
2950 				break;
2951 			case ')':
2952 				/*
2953 				 * End of element: Repeat same element with next
2954 				 * address or continue to next element.
2955 				 */
2956 				addr = (dir == ASC) ? addr + 1 : addr - 1;
2957 				if (addr >= low && addr <= high)
2958 					ptr = elem;
2959 				break;
2960 			default:
2961 				/* Do nothing. */
2962 				break;
2963 			}
2964 	}
2965 
2966 	return 0;
2967 }
2968 #endif
2969 
2970 /* returns 1 if succeeded, 0 if failed, reserve == 0 is unreserve */
2971 static int
2972 slhci_reserve_bustime(struct slhci_softc *sc, struct slhci_pipe *spipe, int
2973     reserve)
2974 {
2975 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
2976 	struct slhci_transfers *t;
2977 	int bustime, max_packet;
2978 
2979 	KASSERT(mutex_owned(&sc->sc_intr_lock));
2980 
2981 	t = &sc->sc_transfers;
2982 	max_packet = UGETW(spipe->pipe.up_endpoint->ue_edesc->wMaxPacketSize);
2983 
2984 	if (spipe->pflags & PF_LS)
2985 		bustime = SLHCI_LS_CONST + SLHCI_LS_DATA_TIME(max_packet);
2986 	else
2987 		bustime = SLHCI_FS_CONST + SLHCI_FS_DATA_TIME(max_packet);
2988 
2989 	if (!reserve) {
2990 		t->reserved_bustime -= bustime;
2991 #ifdef DIAGNOSTIC
2992 		if (t->reserved_bustime < 0) {
2993 			printf("%s: reserved_bustime %d < 0!\n",
2994 			    SC_NAME(sc), t->reserved_bustime);
2995 			DDOLOG("reserved_bustime %d < 0!",
2996 			    t->reserved_bustime, 0, 0, 0);
2997 			t->reserved_bustime = 0;
2998 		}
2999 #endif
3000 		return 1;
3001 	}
3002 
3003 	if (t->reserved_bustime + bustime > SLHCI_RESERVED_BUSTIME) {
3004 		if (ratecheck(&sc->sc_reserved_warn_rate,
3005 		    &reserved_warn_rate))
3006 #ifdef SLHCI_NO_OVERTIME
3007 		{
3008 			printf("%s: Max reserved bus time exceeded! "
3009 			    "Erroring request.\n", SC_NAME(sc));
3010 			DDOLOG("%s: Max reserved bus time exceeded! "
3011 			    "Erroring request.", 0, 0, 0, 0);
3012 		}
3013 		return 0;
3014 #else
3015 		{
3016 			printf("%s: Reserved bus time exceeds %d!\n",
3017 			    SC_NAME(sc), SLHCI_RESERVED_BUSTIME);
3018 			DDOLOG("Reserved bus time exceeds %d!",
3019 			    SLHCI_RESERVED_BUSTIME, 0, 0, 0);
3020 		}
3021 #endif
3022 	}
3023 
3024 	t->reserved_bustime += bustime;
3025 	return 1;
3026 }
3027 
3028 /* Device insertion/removal interrupt */
3029 static void
3030 slhci_insert(struct slhci_softc *sc)
3031 {
3032 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3033 	struct slhci_transfers *t;
3034 
3035 	t = &sc->sc_transfers;
3036 
3037 	KASSERT(mutex_owned(&sc->sc_intr_lock));
3038 
3039 	if (t->flags & F_NODEV)
3040 		slhci_intrchange(sc, 0);
3041 	else {
3042 		slhci_drain(sc);
3043 		slhci_intrchange(sc, SL11_IER_INSERT);
3044 	}
3045 	t->flags ^= F_NODEV;
3046 	t->flags |= F_ROOTINTR|F_CCONNECT;
3047 	DLOG(D_MSG, "INSERT intr: flags after %#jx", t->flags, 0,0,0);
3048 }
3049 
3050 /*
3051  * Data structures and routines to emulate the root hub.
3052  */
3053 
3054 static usbd_status
3055 slhci_clear_feature(struct slhci_softc *sc, unsigned int what)
3056 {
3057 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3058 	struct slhci_transfers *t;
3059 	usbd_status error;
3060 
3061 	t = &sc->sc_transfers;
3062 	error = USBD_NORMAL_COMPLETION;
3063 
3064 	KASSERT(mutex_owned(&sc->sc_intr_lock));
3065 
3066 	if (what == UHF_PORT_POWER) {
3067 		DLOG(D_MSG, "POWER_OFF", 0,0,0,0);
3068 		t->flags &= ~F_POWER;
3069 		if (!(t->flags & F_NODEV))
3070 			t->flags |= F_NODEV|F_CCONNECT|F_ROOTINTR;
3071 		/* for x68k Nereid USB controller */
3072 		if (sc->sc_enable_power && (t->flags & F_REALPOWER)) {
3073 			t->flags &= ~F_REALPOWER;
3074 			sc->sc_enable_power(sc, POWER_OFF);
3075 		}
3076 		slhci_intrchange(sc, 0);
3077 		slhci_drain(sc);
3078 	} else if (what == UHF_C_PORT_CONNECTION) {
3079 		t->flags &= ~F_CCONNECT;
3080 	} else if (what == UHF_C_PORT_RESET) {
3081 		t->flags &= ~F_CRESET;
3082 	} else if (what == UHF_PORT_ENABLE) {
3083 		slhci_drain(sc);
3084 	} else if (what != UHF_PORT_SUSPEND) {
3085 		DDOLOG("ClrPortFeatERR:value=%#.4x", what, 0,0,0);
3086 		error = USBD_IOERROR;
3087 	}
3088 
3089 	return error;
3090 }
3091 
3092 static usbd_status
3093 slhci_set_feature(struct slhci_softc *sc, unsigned int what)
3094 {
3095 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3096 	struct slhci_transfers *t;
3097 	uint8_t r;
3098 
3099 	t = &sc->sc_transfers;
3100 
3101 	KASSERT(mutex_owned(&sc->sc_intr_lock));
3102 
3103 	if (what == UHF_PORT_RESET) {
3104 		if (!(t->flags & F_ACTIVE)) {
3105 			DDOLOG("SET PORT_RESET when not ACTIVE!",
3106 			    0,0,0,0);
3107 			return USBD_INVAL;
3108 		}
3109 		if (!(t->flags & F_POWER)) {
3110 			DDOLOG("SET PORT_RESET without PORT_POWER! flags %p",
3111 			    t->flags, 0,0,0);
3112 			return USBD_INVAL;
3113 		}
3114 		if (t->flags & F_RESET)
3115 			return USBD_NORMAL_COMPLETION;
3116 		DLOG(D_MSG, "RESET flags %#jx", t->flags, 0,0,0);
3117 		slhci_intrchange(sc, 0);
3118 		slhci_drain(sc);
3119 		slhci_write(sc, SL11_CTRL, SL11_CTRL_RESETENGINE);
3120 		/* usb spec says delay >= 10ms, app note 50ms */
3121  		start_cc_time(&t_delay, 50000);
3122 		if (sc->sc_bus.ub_usepolling) {
3123 			DELAY(50000);
3124 			slhci_reset(sc);
3125 		} else {
3126 			t->flags |= F_RESET;
3127 			callout_schedule(&sc->sc_timer, max(mstohz(50), 2));
3128 		}
3129 	} else if (what == UHF_PORT_SUSPEND) {
3130 		printf("%s: USB Suspend not implemented!\n", SC_NAME(sc));
3131 		DDOLOG("USB Suspend not implemented!", 0, 0, 0, 0);
3132 	} else if (what == UHF_PORT_POWER) {
3133 		DLOG(D_MSG, "PORT_POWER", 0,0,0,0);
3134 		/* for x68k Nereid USB controller */
3135 		if (!(t->flags & F_ACTIVE))
3136 			return USBD_INVAL;
3137 		if (t->flags & F_POWER)
3138 			return USBD_NORMAL_COMPLETION;
3139 		if (!(t->flags & F_REALPOWER)) {
3140 			if (sc->sc_enable_power)
3141 				sc->sc_enable_power(sc, POWER_ON);
3142 			t->flags |= F_REALPOWER;
3143 		}
3144 		t->flags |= F_POWER;
3145 		r = slhci_read(sc, SL11_ISR);
3146 		if (r & SL11_ISR_INSERT)
3147 			slhci_write(sc, SL11_ISR, SL11_ISR_INSERT);
3148 		if (r & SL11_ISR_NODEV) {
3149 			slhci_intrchange(sc, SL11_IER_INSERT);
3150 			t->flags |= F_NODEV;
3151 		} else {
3152 			t->flags &= ~F_NODEV;
3153 			t->flags |= F_CCONNECT|F_ROOTINTR;
3154 		}
3155 	} else {
3156 		DDOLOG("SetPortFeatERR=%#.8x", what, 0,0,0);
3157 		return USBD_IOERROR;
3158 	}
3159 
3160 	return USBD_NORMAL_COMPLETION;
3161 }
3162 
3163 static void
3164 slhci_get_status(struct slhci_softc *sc, usb_port_status_t *ps)
3165 {
3166 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3167 	struct slhci_transfers *t;
3168 	unsigned int status, change;
3169 
3170 	t = &sc->sc_transfers;
3171 
3172 	KASSERT(mutex_owned(&sc->sc_intr_lock));
3173 
3174 	/*
3175 	 * We do not have a way to detect over current or babble and
3176 	 * suspend is currently not implemented, so connect and reset
3177 	 * are the only changes that need to be reported.
3178 	 */
3179 	change = 0;
3180 	if (t->flags & F_CCONNECT)
3181 		change |= UPS_C_CONNECT_STATUS;
3182 	if (t->flags & F_CRESET)
3183 		change |= UPS_C_PORT_RESET;
3184 
3185 	status = 0;
3186 	if (!(t->flags & F_NODEV))
3187 		status |= UPS_CURRENT_CONNECT_STATUS;
3188 	if (!(t->flags & F_UDISABLED))
3189 		status |= UPS_PORT_ENABLED;
3190 	if (t->flags & F_RESET)
3191 		status |= UPS_RESET;
3192 	if (t->flags & F_POWER)
3193 		status |= UPS_PORT_POWER;
3194 	if (t->flags & F_LOWSPEED)
3195 		status |= UPS_LOW_SPEED;
3196 	USETW(ps->wPortStatus, status);
3197 	USETW(ps->wPortChange, change);
3198 	DLOG(D_ROOT, "status=%#.4jx, change=%#.4jx", status, change, 0,0);
3199 }
3200 
3201 static int
3202 slhci_roothub_ctrl(struct usbd_bus *bus, usb_device_request_t *req,
3203     void *buf, int buflen)
3204 {
3205 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3206 	struct slhci_softc *sc = SLHCI_BUS2SC(bus);
3207 	struct slhci_transfers *t = &sc->sc_transfers;
3208 	usbd_status error = USBD_IOERROR; /* XXX should be STALL */
3209 	uint16_t len, value, index;
3210 	uint8_t type;
3211 	int actlen = 0;
3212 
3213 	len = UGETW(req->wLength);
3214 	value = UGETW(req->wValue);
3215 	index = UGETW(req->wIndex);
3216 
3217 	type = req->bmRequestType;
3218 
3219 	SLHCI_DEXEC(D_TRACE, slhci_log_req(req));
3220 
3221 	/*
3222 	 * USB requests for hubs have two basic types, standard and class.
3223 	 * Each could potentially have recipients of device, interface,
3224 	 * endpoint, or other.  For the hub class, CLASS_OTHER means the port
3225 	 * and CLASS_DEVICE means the hub.  For standard requests, OTHER
3226 	 * is not used.  Standard request are described in section 9.4 of the
3227 	 * standard, hub class requests in 11.16.  Each request is either read
3228 	 * or write.
3229 	 *
3230 	 * Clear Feature, Set Feature, and Status are defined for each of the
3231 	 * used recipients.  Get Descriptor and Set Descriptor are defined for
3232 	 * both standard and hub class types with different descriptors.
3233 	 * Other requests have only one defined recipient and type.  These
3234 	 * include: Get/Set Address, Get/Set Configuration, Get/Set Interface,
3235 	 * and Synch Frame for standard requests and Get Bus State for hub
3236 	 * class.
3237 	 *
3238 	 * When a device is first powered up it has address 0 until the
3239 	 * address is set.
3240 	 *
3241 	 * Hubs are only allowed to support one interface and may not have
3242 	 * isochronous endpoints.  The results of the related requests are
3243 	 * undefined.
3244 	 *
3245 	 * The standard requires invalid or unsupported requests to return
3246 	 * STALL in the data stage, however this does not work well with
3247 	 * current error handling. XXX
3248 	 *
3249 	 * Some unsupported fields:
3250 	 * Clear Hub Feature is for C_HUB_LOCAL_POWER and C_HUB_OVER_CURRENT
3251 	 * Set Device Features is for ENDPOINT_HALT and DEVICE_REMOTE_WAKEUP
3252 	 * Get Bus State is optional sample of D- and D+ at EOF2
3253 	 */
3254 
3255 	switch (req->bRequest) {
3256 	/* Write Requests */
3257 	case UR_CLEAR_FEATURE:
3258 		if (type == UT_WRITE_CLASS_OTHER) {
3259 			if (index == 1 /* Port */) {
3260 				mutex_enter(&sc->sc_intr_lock);
3261 				error = slhci_clear_feature(sc, value);
3262 				mutex_exit(&sc->sc_intr_lock);
3263 			} else
3264 				DLOG(D_ROOT, "Clear Port Feature "
3265 				    "index = %#.4jx", index, 0,0,0);
3266 		}
3267 		break;
3268 	case UR_SET_FEATURE:
3269 		if (type == UT_WRITE_CLASS_OTHER) {
3270 			if (index == 1 /* Port */) {
3271 				mutex_enter(&sc->sc_intr_lock);
3272 				error = slhci_set_feature(sc, value);
3273 				mutex_exit(&sc->sc_intr_lock);
3274 			} else
3275 				DLOG(D_ROOT, "Set Port Feature "
3276 				    "index = %#.4jx", index, 0,0,0);
3277 		} else if (type != UT_WRITE_CLASS_DEVICE)
3278 			DLOG(D_ROOT, "Set Device Feature "
3279 			    "ENDPOINT_HALT or DEVICE_REMOTE_WAKEUP "
3280 			    "not supported", 0,0,0,0);
3281 		break;
3282 
3283 	/* Read Requests */
3284 	case UR_GET_STATUS:
3285 		if (type == UT_READ_CLASS_OTHER) {
3286 			if (index == 1 /* Port */ && len == /* XXX >=? */
3287 			    sizeof(usb_port_status_t)) {
3288 				mutex_enter(&sc->sc_intr_lock);
3289 				slhci_get_status(sc, (usb_port_status_t *)
3290 				    buf);
3291 				mutex_exit(&sc->sc_intr_lock);
3292 				actlen = sizeof(usb_port_status_t);
3293 				error = USBD_NORMAL_COMPLETION;
3294 			} else
3295 				DLOG(D_ROOT, "Get Port Status index = %#.4jx "
3296 				    "len = %#.4jx", index, len, 0,0);
3297 		} else if (type == UT_READ_CLASS_DEVICE) { /* XXX index? */
3298 			if (len == sizeof(usb_hub_status_t)) {
3299 				DLOG(D_ROOT, "Get Hub Status",
3300 				    0,0,0,0);
3301 				actlen = sizeof(usb_hub_status_t);
3302 				memset(buf, 0, actlen);
3303 				error = USBD_NORMAL_COMPLETION;
3304 			} else
3305 				DLOG(D_ROOT, "Get Hub Status bad len %#.4jx",
3306 				    len, 0,0,0);
3307 		}
3308 		break;
3309 	case UR_GET_DESCRIPTOR:
3310 		if (type == UT_READ_DEVICE) {
3311 			/* value is type (&0xff00) and index (0xff) */
3312 			if (value == (UDESC_DEVICE<<8)) {
3313 				actlen = buflen;
3314 				error = USBD_NORMAL_COMPLETION;
3315 			} else if (value == (UDESC_CONFIG<<8)) {
3316 				struct usb_roothub_descriptors confd;
3317 
3318 				actlen = min(buflen, sizeof(confd));
3319 				memcpy(&confd, buf, actlen);
3320 
3321 				/* 2 mA units */
3322 				confd.urh_confd.bMaxPower = t->max_current;
3323 				memcpy(buf, &confd, actlen);
3324 				error = USBD_NORMAL_COMPLETION;
3325 			} else if (value == ((UDESC_STRING<<8)|1)) {
3326 				/* Vendor */
3327 				actlen = buflen;
3328 				error = USBD_NORMAL_COMPLETION;
3329 			} else if (value == ((UDESC_STRING<<8)|2)) {
3330 				/* Product */
3331 				actlen = usb_makestrdesc((usb_string_descriptor_t *)
3332 				    buf, len, "SL811HS/T root hub");
3333 				error = USBD_NORMAL_COMPLETION;
3334 			} else
3335 				DDOLOG("Unknown Get Descriptor %#.4x",
3336 				    value, 0,0,0);
3337 		} else if (type == UT_READ_CLASS_DEVICE) {
3338 			/* Descriptor number is 0 */
3339 			if (value == (UDESC_HUB<<8)) {
3340 				usb_hub_descriptor_t hubd;
3341 
3342 				actlen = min(buflen, sizeof(hubd));
3343 				memcpy(&hubd, buf, actlen);
3344 				hubd.bHubContrCurrent =
3345 				    500 - t->max_current;
3346 				memcpy(buf, &hubd, actlen);
3347 				error = USBD_NORMAL_COMPLETION;
3348 			} else
3349 				DDOLOG("Unknown Get Hub Descriptor %#.4x",
3350 				    value, 0,0,0);
3351 		}
3352 		break;
3353 	default:
3354 		/* default from usbroothub */
3355 		return buflen;
3356 	}
3357 
3358 	if (error == USBD_NORMAL_COMPLETION)
3359 		return actlen;
3360 
3361 	return -1;
3362 }
3363 
3364 /* End in lock functions. Start debug functions. */
3365 
3366 #ifdef SLHCI_DEBUG
3367 void
3368 slhci_log_buffer(struct usbd_xfer *xfer)
3369 {
3370 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3371 	u_char *buf;
3372 
3373 	if(xfer->ux_length > 0 &&
3374 	    UE_GET_DIR(xfer->ux_pipe->up_endpoint->ue_edesc->bEndpointAddress) ==
3375 	    UE_DIR_IN) {
3376 		buf = xfer->ux_buf;
3377 		DDOLOGBUF(buf, xfer->ux_actlen);
3378 		DDOLOG("len %d actlen %d short %d", xfer->ux_length,
3379 		    xfer->ux_actlen, xfer->ux_length - xfer->ux_actlen, 0);
3380 	}
3381 }
3382 
3383 void
3384 slhci_log_req(usb_device_request_t *r)
3385 {
3386 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3387 	int req, type, value, index, len;
3388 
3389 	req   = r->bRequest;
3390 	type  = r->bmRequestType;
3391 	value = UGETW(r->wValue);
3392 	index = UGETW(r->wIndex);
3393 	len   = UGETW(r->wLength);
3394 
3395 	DDOLOG("request: type %#x", type, 0, 0, 0);
3396 	DDOLOG("request: r=%d,v=%d,i=%d,l=%d ", req, value, index, len);
3397 }
3398 
3399 void
3400 slhci_log_dumpreg(void)
3401 {
3402 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3403 	uint8_t r;
3404 	unsigned int aaddr, alen, baddr, blen;
3405 	static u_char buf[240];
3406 
3407 	r = slhci_read(ssc, SL11_E0CTRL);
3408 	DDOLOG("USB A Host Control = %#.2x", r, 0, 0, 0);
3409 	DDOLOGEPCTRL(r);
3410 
3411 	aaddr = slhci_read(ssc, SL11_E0ADDR);
3412 	DDOLOG("USB A Base Address = %u", aaddr, 0,0,0);
3413 	alen = slhci_read(ssc, SL11_E0LEN);
3414 	DDOLOG("USB A Length = %u", alen, 0,0,0);
3415 	r = slhci_read(ssc, SL11_E0STAT);
3416 	DDOLOG("USB A Status = %#.2x", r, 0,0,0);
3417 	DDOLOGEPSTAT(r);
3418 
3419 	r = slhci_read(ssc, SL11_E0CONT);
3420 	DDOLOG("USB A Remaining or Overflow Length = %u", r, 0,0,0);
3421 	r = slhci_read(ssc, SL11_E1CTRL);
3422 	DDOLOG("USB B Host Control = %#.2x", r, 0,0,0);
3423 	DDOLOGEPCTRL(r);
3424 
3425 	baddr = slhci_read(ssc, SL11_E1ADDR);
3426 	DDOLOG("USB B Base Address = %u", baddr, 0,0,0);
3427 	blen = slhci_read(ssc, SL11_E1LEN);
3428 	DDOLOG("USB B Length = %u", blen, 0,0,0);
3429 	r = slhci_read(ssc, SL11_E1STAT);
3430 	DDOLOG("USB B Status = %#.2x", r, 0,0,0);
3431 	DDOLOGEPSTAT(r);
3432 
3433 	r = slhci_read(ssc, SL11_E1CONT);
3434 	DDOLOG("USB B Remaining or Overflow Length = %u", r, 0,0,0);
3435 
3436 	r = slhci_read(ssc, SL11_CTRL);
3437 	DDOLOG("Control = %#.2x", r, 0,0,0);
3438 	DDOLOGCTRL(r);
3439 
3440 	r = slhci_read(ssc, SL11_IER);
3441 	DDOLOG("Interrupt Enable = %#.2x", r, 0,0,0);
3442 	DDOLOGIER(r);
3443 
3444 	r = slhci_read(ssc, SL11_ISR);
3445 	DDOLOG("Interrupt Status = %#.2x", r, 0,0,0);
3446 	DDOLOGISR(r);
3447 
3448 	r = slhci_read(ssc, SL11_REV);
3449 	DDOLOG("Revision = %#.2x", r, 0,0,0);
3450 	r = slhci_read(ssc, SL811_CSOF);
3451 	DDOLOG("SOF Counter = %#.2x", r, 0,0,0);
3452 
3453 	if (alen && aaddr >= SL11_BUFFER_START && aaddr < SL11_BUFFER_END &&
3454 	    alen <= SL11_MAX_PACKET_SIZE && aaddr + alen <= SL11_BUFFER_END) {
3455 		slhci_read_multi(ssc, aaddr, buf, alen);
3456 		DDOLOG("USBA Buffer: start %u len %u", aaddr, alen, 0,0);
3457 		DDOLOGBUF(buf, alen);
3458 	} else if (alen)
3459 		DDOLOG("USBA Buffer Invalid", 0,0,0,0);
3460 
3461 	if (blen && baddr >= SL11_BUFFER_START && baddr < SL11_BUFFER_END &&
3462 	    blen <= SL11_MAX_PACKET_SIZE && baddr + blen <= SL11_BUFFER_END) {
3463 		slhci_read_multi(ssc, baddr, buf, blen);
3464 		DDOLOG("USBB Buffer: start %u len %u", baddr, blen, 0,0);
3465 		DDOLOGBUF(buf, blen);
3466 	} else if (blen)
3467 		DDOLOG("USBB Buffer Invalid", 0,0,0,0);
3468 }
3469 
3470 void
3471 slhci_log_xfer(struct usbd_xfer *xfer)
3472 {
3473 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3474 	DDOLOG("xfer: length=%u, actlen=%u, flags=%#x, timeout=%u,",
3475 		xfer->ux_length, xfer->ux_actlen, xfer->ux_flags, xfer->ux_timeout);
3476 	DDOLOG("buffer=%p", xfer->ux_buf, 0,0,0);
3477 	slhci_log_req(&xfer->ux_request);
3478 }
3479 
3480 void
3481 slhci_log_spipe(struct slhci_pipe *spipe)
3482 {
3483 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3484 	DDOLOG("spipe %p onlists: AP=%d TO=%d XQ=%d", spipe,
3485 	    gcq_onlist(&spipe->ap) ? 1 : 0,
3486 	    gcq_onlist(&spipe->to) ? 1 : 0,
3487 	    gcq_onlist(&spipe->xq) ? 1 : 0);
3488 	DDOLOG("spipe: xfer %p buffer %p pflags %#x ptype %d",
3489 	    spipe->xfer, spipe->buffer, spipe->pflags, spipe->ptype);
3490 }
3491 
3492 void
3493 slhci_print_intr(void)
3494 {
3495 	unsigned int ier, isr;
3496 	ier = slhci_read(ssc, SL11_IER);
3497 	isr = slhci_read(ssc, SL11_ISR);
3498 	printf("IER: %#x ISR: %#x \n", ier, isr);
3499 }
3500 
3501 #if 0
3502 void
3503 slhci_log_sc(void)
3504 {
3505 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3506 
3507 	struct slhci_transfers *t;
3508 	int i;
3509 
3510 	t = &ssc->sc_transfers;
3511 
3512 	DDOLOG("Flags=%#x", t->flags, 0,0,0);
3513 	DDOLOG("a = %p Alen=%d b = %p Blen=%d", t->spipe[0], t->len[0],
3514 	    t->spipe[1], t->len[1]);
3515 
3516 	for (i=0; i<=Q_MAX; i++)
3517 		DDOLOG("Q %d: %p", i, gcq_hq(&t->q[i]), 0,0);
3518 
3519 	DDOLOG("TIMED: %p", GCQ_ITEM(gcq_hq(&t->to),
3520 	    struct slhci_pipe, to), 0,0,0);
3521 
3522 	DDOLOG("frame=%d rootintr=%p", t->frame, t->rootintr, 0,0);
3523 
3524 	DDOLOG("ub_usepolling=%d", ssc->sc_bus.ub_usepolling, 0, 0, 0);
3525 }
3526 
3527 void
3528 slhci_log_slreq(struct slhci_pipe *r)
3529 {
3530 	SLHCIHIST_FUNC(); SLHCIHIST_CALLED();
3531 	DDOLOG("xfer: %p", r->xfer, 0,0,0);
3532 	DDOLOG("buffer: %p", r->buffer, 0,0,0);
3533 	DDOLOG("bustime: %u", r->bustime, 0,0,0);
3534 	DDOLOG("control: %#x", r->control, 0,0,0);
3535 	DDOLOGEPCTRL(r->control);
3536 
3537 	DDOLOG("pid: %#x", r->tregs[PID], 0,0,0);
3538 	DDOLOG("dev: %u", r->tregs[DEV], 0,0,0);
3539 	DDOLOG("len: %u", r->tregs[LEN], 0,0,0);
3540 
3541 	if (r->xfer)
3542 		slhci_log_xfer(r->xfer);
3543 }
3544 #endif
3545 #endif /* SLHCI_DEBUG */
3546 /* End debug functions. */
3547