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