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