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