Home | History | Annotate | Line # | Download | only in ic
sl811hs.c revision 1.47
      1 /*	$NetBSD: sl811hs.c,v 1.47 2013/10/17 21:24:24 christos 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.47 2013/10/17 21:24:24 christos 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 	spipe = (struct slhci_pipe *)xfer->pipe;
   1344 
   1345 	if (spipe == NULL)
   1346 		goto callback;
   1347 
   1348 	sc = spipe->pipe.device->bus->hci_private;
   1349 
   1350 	KASSERT(mutex_owned(&sc->sc_lock));
   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 
   1369 	sc = pipe->device->bus->hci_private;
   1370 	spipe = (struct slhci_pipe *)pipe;
   1371 
   1372 	DLOG(D_TRACE, "%s close spipe %p spipe->xfer %p",
   1373 	    pnames(spipe->ptype), spipe, spipe->xfer, 0);
   1374 
   1375 	slhci_lock_call(sc, &slhci_close_pipe, spipe, NULL);
   1376 }
   1377 
   1378 void
   1379 slhci_clear_toggle(struct usbd_pipe *pipe)
   1380 {
   1381 	struct slhci_pipe *spipe;
   1382 
   1383 	spipe = (struct slhci_pipe *)pipe;
   1384 
   1385 	DLOG(D_TRACE, "%s toggle spipe %p", pnames(spipe->ptype),
   1386 	    spipe,0,0);
   1387 
   1388 	spipe->pflags &= ~PF_TOGGLE;
   1389 
   1390 #ifdef DIAGNOSTIC
   1391 	if (spipe->xfer != NULL) {
   1392 		struct slhci_softc *sc = (struct slhci_softc
   1393 		    *)pipe->device->bus;
   1394 
   1395 		printf("%s: Clear toggle on transfer in progress! halted\n",
   1396 		    SC_NAME(sc));
   1397 		DDOLOG("%s: Clear toggle on transfer in progress! halted\n",
   1398 		    SC_NAME(sc), 0,0,0);
   1399 		slhci_halt(sc, NULL, NULL);
   1400 	}
   1401 #endif
   1402 }
   1403 
   1404 void
   1405 slhci_poll(struct usbd_bus *bus) /* XXX necessary? */
   1406 {
   1407 	struct slhci_softc *sc;
   1408 
   1409 	sc = bus->hci_private;
   1410 
   1411 	DLOG(D_TRACE, "slhci_poll", 0,0,0,0);
   1412 
   1413 	slhci_lock_call(sc, &slhci_do_poll, NULL, NULL);
   1414 }
   1415 
   1416 void
   1417 slhci_done(struct usbd_xfer *xfer)
   1418 {
   1419 	/* xfer may not be valid here */
   1420 }
   1421 
   1422 void
   1423 slhci_void(void *v) {}
   1424 
   1425 /* End out of lock functions. Start lock entry functions. */
   1426 
   1427 #ifdef SLHCI_MEM_ACCOUNTING
   1428 void
   1429 slhci_mem_use(struct usbd_bus *bus, int val)
   1430 {
   1431 	struct slhci_softc *sc = bus->hci_private;
   1432 	int s;
   1433 
   1434 	mutex_enter(&sc->sc_intr_lock);
   1435 	sc->sc_mem_use += val;
   1436 	mutex_exit(&sc->sc_intr_lock);
   1437 }
   1438 #endif
   1439 
   1440 void
   1441 slhci_reset_entry(void *arg)
   1442 {
   1443 	struct slhci_softc *sc = arg;
   1444 
   1445 	mutex_enter(&sc->sc_intr_lock);
   1446 	slhci_reset(sc);
   1447 	/*
   1448 	 * We cannot call the callback directly since we could then be reset
   1449 	 * again before finishing and need the callout delay for timing.
   1450 	 * Scheduling the callout again before we exit would defeat the reap
   1451 	 * mechanism since we could be unlocked while the reset flag is not
   1452 	 * set. The callback code will check the wait queue.
   1453 	 */
   1454 	slhci_callback_schedule(sc);
   1455 	mutex_exit(&sc->sc_intr_lock);
   1456 }
   1457 
   1458 usbd_status
   1459 slhci_lock_call(struct slhci_softc *sc, LockCallFunc lcf, struct slhci_pipe
   1460     *spipe, struct usbd_xfer *xfer)
   1461 {
   1462 	usbd_status ret;
   1463 
   1464 	mutex_enter(&sc->sc_intr_lock);
   1465 	ret = (*lcf)(sc, spipe, xfer);
   1466 	slhci_main(sc);
   1467 	mutex_exit(&sc->sc_intr_lock);
   1468 
   1469 	return ret;
   1470 }
   1471 
   1472 void
   1473 slhci_start_entry(struct slhci_softc *sc, struct slhci_pipe *spipe)
   1474 {
   1475 	struct slhci_transfers *t;
   1476 
   1477 	mutex_enter(&sc->sc_intr_lock);
   1478 	t = &sc->sc_transfers;
   1479 
   1480 	if (!(t->flags & (F_AINPROG|F_BINPROG))) {
   1481 		slhci_enter_xfer(sc, spipe);
   1482 		slhci_dotransfer(sc);
   1483 		slhci_main(sc);
   1484 	} else {
   1485 		enter_waitq(sc, spipe);
   1486 	}
   1487 	mutex_exit(&sc->sc_intr_lock);
   1488 }
   1489 
   1490 void
   1491 slhci_callback_entry(void *arg)
   1492 {
   1493 	struct slhci_softc *sc;
   1494 	struct slhci_transfers *t;
   1495 
   1496 	sc = (struct slhci_softc *)arg;
   1497 
   1498 	mutex_enter(&sc->sc_intr_lock);
   1499 	t = &sc->sc_transfers;
   1500 	DLOG(D_SOFT, "callback_entry flags %#x", t->flags, 0,0,0);
   1501 
   1502 repeat:
   1503 	slhci_callback(sc);
   1504 
   1505 	if (!gcq_empty(&sc->sc_waitq)) {
   1506 		slhci_enter_xfers(sc);
   1507 		slhci_dotransfer(sc);
   1508 		slhci_waitintr(sc, 0);
   1509 		goto repeat;
   1510 	}
   1511 
   1512 	t->flags &= ~F_CALLBACK;
   1513 	mutex_exit(&sc->sc_intr_lock);
   1514 }
   1515 
   1516 void
   1517 slhci_do_callback(struct slhci_softc *sc, struct usbd_xfer *xfer)
   1518 {
   1519 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   1520 
   1521 	int repeat;
   1522 
   1523 	start_cc_time(&t_callback, (u_int)xfer);
   1524 	mutex_exit(&sc->sc_intr_lock);
   1525 
   1526 	mutex_enter(&sc->sc_lock);
   1527 	repeat = xfer->pipe->repeat;
   1528 	usb_transfer_complete(xfer);
   1529 	mutex_exit(&sc->sc_lock);
   1530 
   1531 	mutex_enter(&sc->sc_intr_lock);
   1532 	stop_cc_time(&t_callback);
   1533 
   1534 	if (repeat && !sc->sc_bus.use_polling)
   1535 		slhci_do_repeat(sc, xfer);
   1536 }
   1537 
   1538 int
   1539 slhci_intr(void *arg)
   1540 {
   1541 	struct slhci_softc *sc = arg;
   1542 	int ret;
   1543 
   1544 	start_cc_time(&t_hard_int, (unsigned int)arg);
   1545 	mutex_enter(&sc->sc_intr_lock);
   1546 
   1547 	ret = slhci_dointr(sc);
   1548 	slhci_main(sc);
   1549 	mutex_exit(&sc->sc_intr_lock);
   1550 
   1551 	stop_cc_time(&t_hard_int);
   1552 	return ret;
   1553 }
   1554 
   1555 /* called with main lock only held, returns with locks released. */
   1556 void
   1557 slhci_main(struct slhci_softc *sc)
   1558 {
   1559 	struct slhci_transfers *t;
   1560 
   1561 	t = &sc->sc_transfers;
   1562 
   1563 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   1564 
   1565 waitcheck:
   1566 	slhci_waitintr(sc, slhci_wait_time);
   1567 
   1568 	/*
   1569 	 * The direct call is needed in the use_polling and disabled cases
   1570 	 * since the soft interrupt is not available.  In the disabled case,
   1571 	 * this code can be reached from the usb detach, after the reaping of
   1572 	 * the soft interrupt.  That test could be !F_ACTIVE, but there is no
   1573 	 * reason not to make the callbacks directly in the other DISABLED
   1574 	 * cases.
   1575 	 */
   1576 	if ((t->flags & F_ROOTINTR) || !gcq_empty(&t->q[Q_CALLBACKS])) {
   1577 		if (__predict_false(sc->sc_bus.use_polling ||
   1578 		    t->flags & F_DISABLED))
   1579 			slhci_callback(sc);
   1580 		else
   1581 			slhci_callback_schedule(sc);
   1582 	}
   1583 
   1584 	if (!gcq_empty(&sc->sc_waitq)) {
   1585 		slhci_enter_xfers(sc);
   1586 		slhci_dotransfer(sc);
   1587 		goto waitcheck;
   1588 	}
   1589 }
   1590 
   1591 /* End lock entry functions. Start in lock function. */
   1592 
   1593 /* Register read/write routines and barriers. */
   1594 #ifdef SLHCI_BUS_SPACE_BARRIERS
   1595 #define BSB(a, b, c, d, e) bus_space_barrier(a, b, c, d, BUS_SPACE_BARRIER_ # e)
   1596 #define BSB_SYNC(a, b, c, d) bus_space_barrier(a, b, c, d, BUS_SPACE_BARRIER_SYNC)
   1597 #else /* now !SLHCI_BUS_SPACE_BARRIERS */
   1598 #define BSB(a, b, c, d, e) __USE(d)
   1599 #define BSB_SYNC(a, b, c, d)
   1600 #endif /* SLHCI_BUS_SPACE_BARRIERS */
   1601 
   1602 static void
   1603 slhci_write(struct slhci_softc *sc, uint8_t addr, uint8_t data)
   1604 {
   1605 	bus_size_t paddr, pdata, pst, psz;
   1606 	bus_space_tag_t iot;
   1607 	bus_space_handle_t ioh;
   1608 
   1609 	paddr = pst = 0;
   1610 	pdata = sc->sc_stride;
   1611 	psz = pdata * 2;
   1612 	iot = sc->sc_iot;
   1613 	ioh = sc->sc_ioh;
   1614 
   1615 	bus_space_write_1(iot, ioh, paddr, addr);
   1616 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
   1617 	bus_space_write_1(iot, ioh, pdata, data);
   1618 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
   1619 }
   1620 
   1621 static uint8_t
   1622 slhci_read(struct slhci_softc *sc, uint8_t addr)
   1623 {
   1624 	bus_size_t paddr, pdata, pst, psz;
   1625 	bus_space_tag_t iot;
   1626 	bus_space_handle_t ioh;
   1627 	uint8_t data;
   1628 
   1629 	paddr = pst = 0;
   1630 	pdata = sc->sc_stride;
   1631 	psz = pdata * 2;
   1632 	iot = sc->sc_iot;
   1633 	ioh = sc->sc_ioh;
   1634 
   1635 	bus_space_write_1(iot, ioh, paddr, addr);
   1636 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_READ);
   1637 	data = bus_space_read_1(iot, ioh, pdata);
   1638 	BSB(iot, ioh, pst, psz, READ_BEFORE_WRITE);
   1639 	return data;
   1640 }
   1641 
   1642 #if 0 /* auto-increment mode broken, see errata doc */
   1643 static void
   1644 slhci_write_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
   1645 {
   1646 	bus_size_t paddr, pdata, pst, psz;
   1647 	bus_space_tag_t iot;
   1648 	bus_space_handle_t ioh;
   1649 
   1650 	paddr = pst = 0;
   1651 	pdata = sc->sc_stride;
   1652 	psz = pdata * 2;
   1653 	iot = sc->sc_iot;
   1654 	ioh = sc->sc_ioh;
   1655 
   1656 	bus_space_write_1(iot, ioh, paddr, addr);
   1657 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
   1658 	bus_space_write_multi_1(iot, ioh, pdata, buf, l);
   1659 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
   1660 }
   1661 
   1662 static void
   1663 slhci_read_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
   1664 {
   1665 	bus_size_t paddr, pdata, pst, psz;
   1666 	bus_space_tag_t iot;
   1667 	bus_space_handle_t ioh;
   1668 
   1669 	paddr = pst = 0;
   1670 	pdata = sc->sc_stride;
   1671 	psz = pdata * 2;
   1672 	iot = sc->sc_iot;
   1673 	ioh = sc->sc_ioh;
   1674 
   1675 	bus_space_write_1(iot, ioh, paddr, addr);
   1676 	BSB(iot, ioh, pst, psz, WRITE_BEFORE_READ);
   1677 	bus_space_read_multi_1(iot, ioh, pdata, buf, l);
   1678 	BSB(iot, ioh, pst, psz, READ_BEFORE_WRITE);
   1679 }
   1680 #else
   1681 static void
   1682 slhci_write_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
   1683 {
   1684 #if 1
   1685 	for (; l; addr++, buf++, l--)
   1686 		slhci_write(sc, addr, *buf);
   1687 #else
   1688 	bus_size_t paddr, pdata, pst, psz;
   1689 	bus_space_tag_t iot;
   1690 	bus_space_handle_t ioh;
   1691 
   1692 	paddr = pst = 0;
   1693 	pdata = sc->sc_stride;
   1694 	psz = pdata * 2;
   1695 	iot = sc->sc_iot;
   1696 	ioh = sc->sc_ioh;
   1697 
   1698 	for (; l; addr++, buf++, l--) {
   1699 		bus_space_write_1(iot, ioh, paddr, addr);
   1700 		BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
   1701 		bus_space_write_1(iot, ioh, pdata, *buf);
   1702 		BSB(iot, ioh, pst, psz, WRITE_BEFORE_WRITE);
   1703 	}
   1704 #endif
   1705 }
   1706 
   1707 static void
   1708 slhci_read_multi(struct slhci_softc *sc, uint8_t addr, uint8_t *buf, int l)
   1709 {
   1710 #if 1
   1711 	for (; l; addr++, buf++, l--)
   1712 		*buf = slhci_read(sc, addr);
   1713 #else
   1714 	bus_size_t paddr, pdata, pst, psz;
   1715 	bus_space_tag_t iot;
   1716 	bus_space_handle_t ioh;
   1717 
   1718 	paddr = pst = 0;
   1719 	pdata = sc->sc_stride;
   1720 	psz = pdata * 2;
   1721 	iot = sc->sc_iot;
   1722 	ioh = sc->sc_ioh;
   1723 
   1724 	for (; l; addr++, buf++, l--) {
   1725 		bus_space_write_1(iot, ioh, paddr, addr);
   1726 		BSB(iot, ioh, pst, psz, WRITE_BEFORE_READ);
   1727 		*buf = bus_space_read_1(iot, ioh, pdata);
   1728 		BSB(iot, ioh, pst, psz, READ_BEFORE_WRITE);
   1729 	}
   1730 #endif
   1731 }
   1732 #endif
   1733 
   1734 /*
   1735  * After calling waitintr it is necessary to either call slhci_callback or
   1736  * schedule the callback if necessary.  The callback cannot be called directly
   1737  * from the hard interrupt since it interrupts at a high IPL and callbacks
   1738  * can do copyout and such.
   1739  */
   1740 static void
   1741 slhci_waitintr(struct slhci_softc *sc, int wait_time)
   1742 {
   1743 	struct slhci_transfers *t;
   1744 
   1745 	t = &sc->sc_transfers;
   1746 
   1747 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   1748 
   1749 	if (__predict_false(sc->sc_bus.use_polling))
   1750 		wait_time = 12000;
   1751 
   1752 	while (t->pend <= wait_time) {
   1753 		DLOG(D_WAIT, "waiting... frame %d pend %d flags %#x",
   1754 		    t->frame, t->pend, t->flags, 0);
   1755 		LK_SLASSERT(t->flags & F_ACTIVE, sc, NULL, NULL, return);
   1756 		LK_SLASSERT(t->flags & (F_AINPROG|F_BINPROG), sc, NULL, NULL,
   1757 		    return);
   1758 		slhci_dointr(sc);
   1759 	}
   1760 }
   1761 
   1762 static int
   1763 slhci_dointr(struct slhci_softc *sc)
   1764 {
   1765 	struct slhci_transfers *t;
   1766 	struct slhci_pipe *tosp;
   1767 	uint8_t r;
   1768 
   1769 	t = &sc->sc_transfers;
   1770 
   1771 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   1772 
   1773 	if (sc->sc_ier == 0)
   1774 		return 0;
   1775 
   1776 	r = slhci_read(sc, SL11_ISR);
   1777 
   1778 #ifdef SLHCI_DEBUG
   1779 	if (slhci_debug & SLHCI_D_INTR && r & sc->sc_ier &&
   1780 	    ((r & ~(SL11_ISR_SOF|SL11_ISR_DATA)) || slhci_debug &
   1781 	    SLHCI_D_SOF)) {
   1782 		uint8_t e, f;
   1783 
   1784 		e = slhci_read(sc, SL11_IER);
   1785 		f = slhci_read(sc, SL11_CTRL);
   1786 		DDOLOG("Flags=%#x IER=%#x ISR=%#x", t->flags, e, r, 0);
   1787 		DDOLOGFLAG8("Status=", r, "D+", (f & SL11_CTRL_SUSPEND) ?
   1788 		    "RESUME" : "NODEV", "INSERT", "SOF", "res", "BABBLE",
   1789 		    "USBB", "USBA");
   1790 	}
   1791 #endif
   1792 
   1793 	/*
   1794 	 * check IER for corruption occasionally.  Assume that the above
   1795 	 * sc_ier == 0 case works correctly.
   1796 	 */
   1797 	if (__predict_false(sc->sc_ier_check++ > SLHCI_IER_CHECK_FREQUENCY)) {
   1798 		sc->sc_ier_check = 0;
   1799 		if (sc->sc_ier != slhci_read(sc, SL11_IER)) {
   1800 			printf("%s: IER value corrupted! halted\n",
   1801 			    SC_NAME(sc));
   1802 			DDOLOG("%s: IER value corrupted! halted\n",
   1803 			    SC_NAME(sc), 0,0,0);
   1804 			slhci_halt(sc, NULL, NULL);
   1805 			return 1;
   1806 		}
   1807 	}
   1808 
   1809 	r &= sc->sc_ier;
   1810 
   1811 	if (r == 0)
   1812 		return 0;
   1813 
   1814 	sc->sc_ier_check = 0;
   1815 
   1816 	slhci_write(sc, SL11_ISR, r);
   1817 	BSB_SYNC(sc->iot, sc->ioh, sc->pst, sc->psz);
   1818 
   1819 	/* If we have an insertion event we do not care about anything else. */
   1820 	if (__predict_false(r & SL11_ISR_INSERT)) {
   1821 		slhci_insert(sc);
   1822 		return 1;
   1823 	}
   1824 
   1825 	stop_cc_time(&t_intr);
   1826 	start_cc_time(&t_intr, r);
   1827 
   1828 	if (r & SL11_ISR_SOF) {
   1829 		t->frame++;
   1830 
   1831 		gcq_merge_tail(&t->q[Q_CB], &t->q[Q_NEXT_CB]);
   1832 
   1833 		/*
   1834 		 * SOFCHECK flags are cleared in tstart.  Two flags are needed
   1835 		 * since the first SOF interrupt processed after the transfer
   1836 		 * is started might have been generated before the transfer
   1837 		 * was started.
   1838 		 */
   1839 		if (__predict_false(t->flags & F_SOFCHECK2 && t->flags &
   1840 		    (F_AINPROG|F_BINPROG))) {
   1841 			printf("%s: Missed transfer completion. halted\n",
   1842 			    SC_NAME(sc));
   1843 			DDOLOG("%s: Missed transfer completion. halted\n",
   1844 			    SC_NAME(sc), 0,0,0);
   1845 			slhci_halt(sc, NULL, NULL);
   1846 			return 1;
   1847 		} else if (t->flags & F_SOFCHECK1) {
   1848 			t->flags |= F_SOFCHECK2;
   1849 		} else
   1850 			t->flags |= F_SOFCHECK1;
   1851 
   1852 		if (t->flags & F_CHANGE)
   1853 			t->flags |= F_ROOTINTR;
   1854 
   1855 		while (__predict_true(GOT_FIRST_TO(tosp, t)) &&
   1856 		    __predict_false(tosp->to_frame <= t->frame)) {
   1857 			tosp->xfer->status = USBD_TIMEOUT;
   1858 			slhci_do_abort(sc, tosp, tosp->xfer);
   1859 			enter_callback(t, tosp);
   1860 		}
   1861 
   1862 		/*
   1863 		 * Start any waiting transfers right away.  If none, we will
   1864 		 * start any new transfers later.
   1865 		 */
   1866 		slhci_tstart(sc);
   1867 	}
   1868 
   1869 	if (r & (SL11_ISR_USBA|SL11_ISR_USBB)) {
   1870 		int ab;
   1871 
   1872 		if ((r & (SL11_ISR_USBA|SL11_ISR_USBB)) ==
   1873 		    (SL11_ISR_USBA|SL11_ISR_USBB)) {
   1874 			if (!(t->flags & (F_AINPROG|F_BINPROG)))
   1875 				return 1; /* presume card pulled */
   1876 
   1877 			LK_SLASSERT((t->flags & (F_AINPROG|F_BINPROG)) !=
   1878 			    (F_AINPROG|F_BINPROG), sc, NULL, NULL, return 1);
   1879 
   1880 			/*
   1881 			 * This should never happen (unless card removal just
   1882 			 * occurred) but appeared frequently when both
   1883 			 * transfers were started at the same time and was
   1884 			 * accompanied by data corruption.  It still happens
   1885 			 * at times.  I have not seen data correption except
   1886 			 * when the STATUS bit gets set, which now causes the
   1887 			 * driver to halt, however this should still not
   1888 			 * happen so the warning is kept.  See comment in
   1889 			 * abdone, below.
   1890 			 */
   1891 			printf("%s: Transfer reported done but not started! "
   1892 			    "Verify data integrity if not detaching. "
   1893 			    " flags %#x r %x\n", SC_NAME(sc), t->flags, r);
   1894 
   1895 			if (!(t->flags & F_AINPROG))
   1896 				r &= ~SL11_ISR_USBA;
   1897 			else
   1898 				r &= ~SL11_ISR_USBB;
   1899 		}
   1900 		t->pend = INT_MAX;
   1901 
   1902 		if (r & SL11_ISR_USBA)
   1903 			ab = A;
   1904 		else
   1905 			ab = B;
   1906 
   1907 		/*
   1908 		 * This happens when a low speed device is attached to
   1909 		 * a hub with chip rev 1.5.  SOF stops, but a few transfers
   1910 		 * still work before causing this error.
   1911 		 */
   1912 		if (!(t->flags & (ab ? F_BINPROG : F_AINPROG))) {
   1913 			printf("%s: %s done but not in progress! halted\n",
   1914 			    SC_NAME(sc), ab ? "B" : "A");
   1915 			DDOLOG("%s: %s done but not in progress! halted\n",
   1916 			    SC_NAME(sc), ab ? "B" : "A", 0,0);
   1917 			slhci_halt(sc, NULL, NULL);
   1918 			return 1;
   1919 		}
   1920 
   1921 		t->flags &= ~(ab ? F_BINPROG : F_AINPROG);
   1922 		slhci_tstart(sc);
   1923 		stop_cc_time(&t_ab[ab]);
   1924 		start_cc_time(&t_abdone, t->flags);
   1925 		slhci_abdone(sc, ab);
   1926 		stop_cc_time(&t_abdone);
   1927 	}
   1928 
   1929 	slhci_dotransfer(sc);
   1930 
   1931 	return 1;
   1932 }
   1933 
   1934 static void
   1935 slhci_abdone(struct slhci_softc *sc, int ab)
   1936 {
   1937 	struct slhci_transfers *t;
   1938 	struct slhci_pipe *spipe;
   1939 	struct usbd_xfer *xfer;
   1940 	uint8_t status, buf_start;
   1941 	uint8_t *target_buf;
   1942 	unsigned int actlen;
   1943 	int head;
   1944 
   1945 	t = &sc->sc_transfers;
   1946 
   1947 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   1948 
   1949 	DLOG(D_TRACE, "ABDONE flags %#x", t->flags, 0,0,0);
   1950 
   1951 	DLOG(D_MSG, "DONE %s spipe %p len %d xfer %p", ab ? "B" : "A",
   1952 	    t->spipe[ab], t->len[ab], t->spipe[ab] ?
   1953 	    t->spipe[ab]->xfer : NULL);
   1954 
   1955 	spipe = t->spipe[ab];
   1956 
   1957 	/*
   1958 	 * skip this one if aborted; do not call return from the rest of the
   1959 	 * function unless halting, else t->len will not be cleared.
   1960 	 */
   1961 	if (spipe == NULL)
   1962 		goto done;
   1963 
   1964 	t->spipe[ab] = NULL;
   1965 
   1966 	xfer = spipe->xfer;
   1967 
   1968 	gcq_remove(&spipe->to);
   1969 
   1970 	LK_SLASSERT(xfer != NULL, sc, spipe, NULL, return);
   1971 
   1972 	status = slhci_read(sc, slhci_tregs[ab][STAT]);
   1973 
   1974 	/*
   1975 	 * I saw no status or remaining length greater than the requested
   1976 	 * length in early driver versions in circumstances I assumed caused
   1977 	 * excess power draw.  I am no longer able to reproduce this when
   1978 	 * causing excess power draw circumstances.
   1979 	 *
   1980 	 * Disabling a power check and attaching aue to a keyboard and hub
   1981 	 * that is directly attached (to CFU1U, 100mA max, aue 160mA, keyboard
   1982 	 * 98mA) sometimes works and sometimes fails to configure.  After
   1983 	 * removing the aue and attaching a self-powered umass dvd reader
   1984 	 * (unknown if it draws power from the host also) soon a single Error
   1985 	 * status occurs then only timeouts. The controller soon halts freeing
   1986 	 * memory due to being ONQU instead of BUSY.  This may be the same
   1987 	 * basic sequence that caused the no status/bad length errors.  The
   1988 	 * umass device seems to work (better at least) with the keyboard hub
   1989 	 * when not first attaching aue (tested once reading an approximately
   1990 	 * 200MB file).
   1991 	 *
   1992 	 * Overflow can indicate that the device and host disagree about how
   1993 	 * much data has been transfered.  This may indicate a problem at any
   1994 	 * point during the transfer, not just when the error occurs.  It may
   1995 	 * indicate data corruption.  A warning message is printed.
   1996 	 *
   1997 	 * Trying to use both A and B transfers at the same time results in
   1998 	 * incorrect transfer completion ISR reports and the status will then
   1999 	 * include SL11_EPSTAT_SETUP, which is apparently set while the
   2000 	 * transfer is in progress.  I also noticed data corruption, even
   2001 	 * after waiting for the transfer to complete. The driver now avoids
   2002 	 * trying to start both at the same time.
   2003 	 *
   2004 	 * I had accidently initialized the B registers before they were valid
   2005 	 * in some driver versions.  Since every other performance enhancing
   2006 	 * feature has been confirmed buggy in the errata doc, I have not
   2007 	 * tried both transfers at once again with the documented
   2008 	 * initialization order.
   2009 	 *
   2010 	 * However, I have seen this problem again ("done but not started"
   2011 	 * errors), which in some cases cases the SETUP status bit to remain
   2012 	 * set on future transfers.  In other cases, the SETUP bit is not set
   2013 	 * and no data corruption occurs.  This occured while using both umass
   2014 	 * and aue on a powered hub (maybe triggered by some local activity
   2015 	 * also) and needs several reads of the 200MB file to trigger.  The
   2016 	 * driver now halts if SETUP is detected.
   2017  	 */
   2018 
   2019 	actlen = 0;
   2020 
   2021 	if (__predict_false(!status)) {
   2022 		DDOLOG("no status! xfer %p spipe %p", xfer, spipe, 0,0);
   2023 		printf("%s: no status! halted\n", SC_NAME(sc));
   2024 		slhci_halt(sc, spipe, xfer);
   2025 		return;
   2026 	}
   2027 
   2028 #ifdef SLHCI_DEBUG
   2029 	if (slhci_debug & SLHCI_D_NAK || (status & SL11_EPSTAT_ERRBITS) !=
   2030 	    SL11_EPSTAT_NAK)
   2031 		DLOGFLAG8(D_XFER, "STATUS=", status, "STALL", "NAK",
   2032 		    "Overflow", "Setup", "Data Toggle", "Timeout", "Error",
   2033 		    "ACK");
   2034 #endif
   2035 
   2036 	if (!(status & SL11_EPSTAT_ERRBITS)) {
   2037 		unsigned int cont;
   2038 		cont = slhci_read(sc, slhci_tregs[ab][CONT]);
   2039 		if (cont != 0)
   2040 			DLOG(D_XFER, "cont %d len %d", cont,
   2041 			    spipe->tregs[LEN], 0,0);
   2042 		if (__predict_false(cont > spipe->tregs[LEN])) {
   2043 			DDOLOG("cont > len! cont %d len %d xfer->length %d "
   2044 			    "spipe %p", cont, spipe->tregs[LEN], xfer->length,
   2045 			    spipe);
   2046 			printf("%s: cont > len! cont %d len %d xfer->length "
   2047 			    "%d", SC_NAME(sc), cont, spipe->tregs[LEN],
   2048 			    xfer->length);
   2049 			slhci_halt(sc, spipe, xfer);
   2050 			return;
   2051 		} else {
   2052 			spipe->nerrs = 0;
   2053 			actlen = spipe->tregs[LEN] - cont;
   2054 		}
   2055 	}
   2056 
   2057 	/* Actual copyin done after starting next transfer. */
   2058 	if (actlen && (spipe->tregs[PID] & SL11_PID_BITS) == SL11_PID_IN) {
   2059 		target_buf = spipe->buffer;
   2060 		buf_start = spipe->tregs[ADR];
   2061 	} else {
   2062 		target_buf = NULL;
   2063 		buf_start = 0; /* XXX gcc uninitialized warnings */
   2064 	}
   2065 
   2066 	if (status & SL11_EPSTAT_ERRBITS) {
   2067 		status &= SL11_EPSTAT_ERRBITS;
   2068 		if (status & SL11_EPSTAT_SETUP) {
   2069 			printf("%s: Invalid controller state detected! "
   2070 			    "halted\n", SC_NAME(sc));
   2071 			DDOLOG("%s: Invalid controller state detected! "
   2072 			    "halted\n", SC_NAME(sc), 0,0,0);
   2073 			slhci_halt(sc, spipe, xfer);
   2074 			return;
   2075 		} else if (__predict_false(sc->sc_bus.use_polling)) {
   2076 			if (status == SL11_EPSTAT_STALL)
   2077 				xfer->status = USBD_STALLED;
   2078 			else if (status == SL11_EPSTAT_TIMEOUT)
   2079 				xfer->status = USBD_TIMEOUT;
   2080 			else if (status == SL11_EPSTAT_NAK)
   2081 				xfer->status = USBD_TIMEOUT; /*XXX*/
   2082 			else
   2083 				xfer->status = USBD_IOERROR;
   2084 			head = Q_CALLBACKS;
   2085 		} else if (status == SL11_EPSTAT_NAK) {
   2086 			if (spipe->pipe.interval) {
   2087 				spipe->lastframe = spipe->frame =
   2088 				    t->frame + spipe->pipe.interval;
   2089 				slhci_queue_timed(sc, spipe);
   2090 				goto queued;
   2091 			}
   2092 			head = Q_NEXT_CB;
   2093 		} else if (++spipe->nerrs > SLHCI_MAX_RETRIES ||
   2094 		    status == SL11_EPSTAT_STALL) {
   2095 			if (status == SL11_EPSTAT_STALL)
   2096 				xfer->status = USBD_STALLED;
   2097 			else if (status == SL11_EPSTAT_TIMEOUT)
   2098 				xfer->status = USBD_TIMEOUT;
   2099 			else
   2100 				xfer->status = USBD_IOERROR;
   2101 
   2102 			DLOG(D_ERR, "Max retries reached! status %#x "
   2103 			    "xfer->status %#x", status, xfer->status, 0,0);
   2104 			DLOGFLAG8(D_ERR, "STATUS=", status, "STALL",
   2105 			    "NAK", "Overflow", "Setup", "Data Toggle",
   2106 			    "Timeout", "Error", "ACK");
   2107 
   2108 			if (status == SL11_EPSTAT_OVERFLOW &&
   2109 			    ratecheck(&sc->sc_overflow_warn_rate,
   2110 			    &overflow_warn_rate)) {
   2111 				printf("%s: Overflow condition: "
   2112 				    "data corruption possible\n",
   2113 				    SC_NAME(sc));
   2114 				DDOLOG("%s: Overflow condition: "
   2115 				    "data corruption possible\n",
   2116 				    SC_NAME(sc), 0,0,0);
   2117 			}
   2118 			head = Q_CALLBACKS;
   2119 		} else {
   2120 			head = Q_NEXT_CB;
   2121 		}
   2122 	} else if (spipe->ptype == PT_CTRL_SETUP) {
   2123 		spipe->tregs[PID] = spipe->newpid;
   2124 
   2125 		if (xfer->length) {
   2126 			LK_SLASSERT(spipe->newlen[1] != 0, sc, spipe, xfer,
   2127 			    return);
   2128 			spipe->tregs[LEN] = spipe->newlen[1];
   2129 			spipe->bustime = spipe->newbustime[1];
   2130 			spipe->buffer = KERNADDR(&xfer->dmabuf, 0);
   2131 			spipe->ptype = PT_CTRL_DATA;
   2132 		} else {
   2133 status_setup:
   2134 			/* CTRL_DATA swaps direction in PID then jumps here */
   2135 			spipe->tregs[LEN] = 0;
   2136 			if (spipe->pflags & PF_LS)
   2137 				spipe->bustime = SLHCI_LS_CONST;
   2138 			else
   2139 				spipe->bustime = SLHCI_FS_CONST;
   2140 			spipe->ptype = PT_CTRL_STATUS;
   2141 			spipe->buffer = NULL;
   2142 		}
   2143 
   2144 		/* Status or first data packet must be DATA1. */
   2145 		spipe->control |= SL11_EPCTRL_DATATOGGLE;
   2146 		if ((spipe->tregs[PID] & SL11_PID_BITS) == SL11_PID_IN)
   2147 			spipe->control &= ~SL11_EPCTRL_DIRECTION;
   2148 		else
   2149 			spipe->control |= SL11_EPCTRL_DIRECTION;
   2150 
   2151 		head = Q_CB;
   2152 	} else if (spipe->ptype == PT_CTRL_STATUS) {
   2153 		head = Q_CALLBACKS;
   2154 	} else { /* bulk, intr, control data */
   2155 		xfer->actlen += actlen;
   2156 		spipe->control ^= SL11_EPCTRL_DATATOGGLE;
   2157 
   2158 		if (actlen == spipe->tregs[LEN] && (xfer->length >
   2159 		    xfer->actlen || spipe->wantshort)) {
   2160 			spipe->buffer += actlen;
   2161 			LK_SLASSERT(xfer->length >= xfer->actlen, sc,
   2162 			    spipe, xfer, return);
   2163 			if (xfer->length - xfer->actlen < actlen) {
   2164 				spipe->wantshort = 0;
   2165 				spipe->tregs[LEN] = spipe->newlen[0];
   2166 				spipe->bustime = spipe->newbustime[0];
   2167 				LK_SLASSERT(xfer->actlen +
   2168 				    spipe->tregs[LEN] == xfer->length, sc,
   2169 				    spipe, xfer, return);
   2170 			}
   2171 			head = Q_CB;
   2172 		} else if (spipe->ptype == PT_CTRL_DATA) {
   2173 			spipe->tregs[PID] ^= SLHCI_PID_SWAP_IN_OUT;
   2174 			goto status_setup;
   2175 		} else {
   2176 			if (spipe->ptype == PT_INTR) {
   2177 				spipe->lastframe +=
   2178 				    spipe->pipe.interval;
   2179 				/*
   2180 				 * If ack, we try to keep the
   2181 				 * interrupt rate by using lastframe
   2182 				 * instead of the current frame.
   2183 				 */
   2184 				spipe->frame = spipe->lastframe +
   2185 				    spipe->pipe.interval;
   2186 			}
   2187 
   2188 			/*
   2189 			 * Set the toggle for the next transfer.  It
   2190 			 * has already been toggled above, so the
   2191 			 * current setting will apply to the next
   2192 			 * transfer.
   2193 			 */
   2194 			if (spipe->control & SL11_EPCTRL_DATATOGGLE)
   2195 				spipe->pflags |= PF_TOGGLE;
   2196 			else
   2197 				spipe->pflags &= ~PF_TOGGLE;
   2198 
   2199 			head = Q_CALLBACKS;
   2200 		}
   2201 	}
   2202 
   2203 	if (head == Q_CALLBACKS) {
   2204 		gcq_remove(&spipe->to);
   2205 
   2206 	 	if (xfer->status == USBD_IN_PROGRESS) {
   2207 			LK_SLASSERT(xfer->actlen <= xfer->length, sc,
   2208 			    spipe, xfer, return);
   2209 			xfer->status = USBD_NORMAL_COMPLETION;
   2210 #if 0 /* usb_transfer_complete will do this */
   2211 			if (xfer->length == xfer->actlen || xfer->flags &
   2212 			    USBD_SHORT_XFER_OK)
   2213 				xfer->status = USBD_NORMAL_COMPLETION;
   2214 			else
   2215 				xfer->status = USBD_SHORT_XFER;
   2216 #endif
   2217 		}
   2218 	}
   2219 
   2220 	enter_q(t, spipe, head);
   2221 
   2222 queued:
   2223 	if (target_buf != NULL) {
   2224 		slhci_dotransfer(sc);
   2225 		start_cc_time(&t_copy_from_dev, actlen);
   2226 		slhci_read_multi(sc, buf_start, target_buf, actlen);
   2227 		stop_cc_time(&t_copy_from_dev);
   2228 		DLOGBUF(D_BUF, target_buf, actlen);
   2229 		t->pend -= SLHCI_FS_CONST + SLHCI_FS_DATA_TIME(actlen);
   2230 	}
   2231 
   2232 done:
   2233 	t->len[ab] = -1;
   2234 }
   2235 
   2236 static void
   2237 slhci_tstart(struct slhci_softc *sc)
   2238 {
   2239 	struct slhci_transfers *t;
   2240 	struct slhci_pipe *spipe;
   2241 	int remaining_bustime;
   2242 
   2243 	t = &sc->sc_transfers;
   2244 
   2245 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2246 
   2247 	if (!(t->flags & (F_AREADY|F_BREADY)))
   2248 		return;
   2249 
   2250 	if (t->flags & (F_AINPROG|F_BINPROG|F_DISABLED))
   2251 		return;
   2252 
   2253 	/*
   2254 	 * We have about 6 us to get from the bus time check to
   2255 	 * starting the transfer or we might babble or the chip might fail to
   2256 	 * signal transfer complete.  This leaves no time for any other
   2257 	 * interrupts.
   2258 	 */
   2259 	remaining_bustime = (int)(slhci_read(sc, SL811_CSOF)) << 6;
   2260 	remaining_bustime -= SLHCI_END_BUSTIME;
   2261 
   2262 	/*
   2263 	 * Start one transfer only, clearing any aborted transfers that are
   2264 	 * not yet in progress and skipping missed isoc. It is easier to copy
   2265 	 * & paste most of the A/B sections than to make the logic work
   2266 	 * otherwise and this allows better constant use.
   2267 	 */
   2268 	if (t->flags & F_AREADY) {
   2269 		spipe = t->spipe[A];
   2270 		if (spipe == NULL) {
   2271 			t->flags &= ~F_AREADY;
   2272 			t->len[A] = -1;
   2273 		} else if (remaining_bustime >= spipe->bustime) {
   2274 			t->flags &= ~(F_AREADY|F_SOFCHECK1|F_SOFCHECK2);
   2275 			t->flags |= F_AINPROG;
   2276 			start_cc_time(&t_ab[A], spipe->tregs[LEN]);
   2277 			slhci_write(sc, SL11_E0CTRL, spipe->control);
   2278 			goto pend;
   2279 		}
   2280 	}
   2281 	if (t->flags & F_BREADY) {
   2282 		spipe = t->spipe[B];
   2283 		if (spipe == NULL) {
   2284 			t->flags &= ~F_BREADY;
   2285 			t->len[B] = -1;
   2286 		} else if (remaining_bustime >= spipe->bustime) {
   2287 			t->flags &= ~(F_BREADY|F_SOFCHECK1|F_SOFCHECK2);
   2288 			t->flags |= F_BINPROG;
   2289 			start_cc_time(&t_ab[B], spipe->tregs[LEN]);
   2290 			slhci_write(sc, SL11_E1CTRL, spipe->control);
   2291 pend:
   2292 			t->pend = spipe->bustime;
   2293 		}
   2294 	}
   2295 }
   2296 
   2297 static void
   2298 slhci_dotransfer(struct slhci_softc *sc)
   2299 {
   2300 	struct slhci_transfers *t;
   2301 	struct slhci_pipe *spipe;
   2302 	int ab, i;
   2303 
   2304 	t = &sc->sc_transfers;
   2305 
   2306 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2307 
   2308  	while ((t->len[A] == -1 || t->len[B] == -1) &&
   2309 	    (GOT_FIRST_TIMED_COND(spipe, t, spipe->frame <= t->frame) ||
   2310 	    GOT_FIRST_CB(spipe, t))) {
   2311 		LK_SLASSERT(spipe->xfer != NULL, sc, spipe, NULL, return);
   2312 		LK_SLASSERT(spipe->ptype != PT_ROOT_CTRL && spipe->ptype !=
   2313 		    PT_ROOT_INTR, sc, spipe, NULL, return);
   2314 
   2315 		/* Check that this transfer can fit in the remaining memory. */
   2316 		if (t->len[A] + t->len[B] + spipe->tregs[LEN] + 1 >
   2317 		    SL11_MAX_PACKET_SIZE) {
   2318 			DLOG(D_XFER, "Transfer does not fit. alen %d blen %d "
   2319 			    "len %d", t->len[A], t->len[B], spipe->tregs[LEN],
   2320 			    0);
   2321 			return;
   2322 		}
   2323 
   2324 		gcq_remove(&spipe->xq);
   2325 
   2326 		if (t->len[A] == -1) {
   2327 			ab = A;
   2328 			spipe->tregs[ADR] = SL11_BUFFER_START;
   2329 		} else {
   2330 			ab = B;
   2331 			spipe->tregs[ADR] = SL11_BUFFER_END -
   2332 			    spipe->tregs[LEN];
   2333 		}
   2334 
   2335 		t->len[ab] = spipe->tregs[LEN];
   2336 
   2337 		if (spipe->tregs[LEN] && (spipe->tregs[PID] & SL11_PID_BITS)
   2338 		    != SL11_PID_IN) {
   2339 			start_cc_time(&t_copy_to_dev,
   2340 			    spipe->tregs[LEN]);
   2341 			slhci_write_multi(sc, spipe->tregs[ADR],
   2342 			    spipe->buffer, spipe->tregs[LEN]);
   2343 			stop_cc_time(&t_copy_to_dev);
   2344 			t->pend -= SLHCI_FS_CONST +
   2345 			    SLHCI_FS_DATA_TIME(spipe->tregs[LEN]);
   2346 		}
   2347 
   2348 		DLOG(D_MSG, "NEW TRANSFER %s flags %#x alen %d blen %d",
   2349 		    ab ? "B" : "A", t->flags, t->len[0], t->len[1]);
   2350 
   2351 		if (spipe->tregs[LEN])
   2352 			i = 0;
   2353 		else
   2354 			i = 1;
   2355 
   2356 		for (; i <= 3; i++)
   2357 			if (t->current_tregs[ab][i] != spipe->tregs[i]) {
   2358 				t->current_tregs[ab][i] = spipe->tregs[i];
   2359 				slhci_write(sc, slhci_tregs[ab][i],
   2360 				    spipe->tregs[i]);
   2361 			}
   2362 
   2363 		DLOG(D_SXFER, "Transfer len %d pid %#x dev %d type %s",
   2364 		    spipe->tregs[LEN], spipe->tregs[PID], spipe->tregs[DEV],
   2365 	    	    pnames(spipe->ptype));
   2366 
   2367 		t->spipe[ab] = spipe;
   2368 		t->flags |= ab ? F_BREADY : F_AREADY;
   2369 
   2370 		slhci_tstart(sc);
   2371 	}
   2372 }
   2373 
   2374 /*
   2375  * slhci_callback is called after the lock is taken from splusb.
   2376  */
   2377 static void
   2378 slhci_callback(struct slhci_softc *sc)
   2379 {
   2380 	struct slhci_transfers *t;
   2381 	struct slhci_pipe *spipe;
   2382 	struct usbd_xfer *xfer;
   2383 
   2384 	t = &sc->sc_transfers;
   2385 
   2386 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2387 
   2388 	DLOG(D_SOFT, "CB flags %#x", t->flags, 0,0,0);
   2389 	for (;;) {
   2390 		if (__predict_false(t->flags & F_ROOTINTR)) {
   2391 			t->flags &= ~F_ROOTINTR;
   2392 			if (t->rootintr != NULL) {
   2393 				u_char *p;
   2394 
   2395 				p = KERNADDR(&t->rootintr->dmabuf, 0);
   2396 				p[0] = 2;
   2397 				t->rootintr->actlen = 1;
   2398 				t->rootintr->status = USBD_NORMAL_COMPLETION;
   2399 				xfer = t->rootintr;
   2400 				goto do_callback;
   2401 			}
   2402 		}
   2403 
   2404 
   2405 		if (!DEQUEUED_CALLBACK(spipe, t))
   2406 			return;
   2407 
   2408 		xfer = spipe->xfer;
   2409 		LK_SLASSERT(xfer != NULL, sc, spipe, NULL, return);
   2410 		spipe->xfer = NULL;
   2411 		DLOG(D_XFER, "xfer callback length %d actlen %d spipe %x "
   2412 		    "type %s", xfer->length, xfer->actlen, spipe,
   2413 		    pnames(spipe->ptype));
   2414 do_callback:
   2415 		slhci_do_callback(sc, xfer);
   2416 	}
   2417 }
   2418 
   2419 static void
   2420 slhci_enter_xfer(struct slhci_softc *sc, struct slhci_pipe *spipe)
   2421 {
   2422 	struct slhci_transfers *t;
   2423 
   2424 	t = &sc->sc_transfers;
   2425 
   2426 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2427 
   2428 	if (__predict_false(t->flags & F_DISABLED) ||
   2429 	    __predict_false(spipe->pflags & PF_GONE)) {
   2430 		DLOG(D_MSG, "slhci_enter_xfer: DISABLED or GONE", 0,0,0,0);
   2431 		spipe->xfer->status = USBD_CANCELLED;
   2432 	}
   2433 
   2434 	if (spipe->xfer->status == USBD_IN_PROGRESS) {
   2435 		if (spipe->xfer->timeout) {
   2436 			spipe->to_frame = t->frame + spipe->xfer->timeout;
   2437 			slhci_xfer_timer(sc, spipe);
   2438 		}
   2439 		if (spipe->pipe.interval)
   2440 			slhci_queue_timed(sc, spipe);
   2441 		else
   2442 			enter_q(t, spipe, Q_CB);
   2443 	} else
   2444 		enter_callback(t, spipe);
   2445 }
   2446 
   2447 static void
   2448 slhci_enter_xfers(struct slhci_softc *sc)
   2449 {
   2450 	struct slhci_pipe *spipe;
   2451 
   2452 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2453 
   2454 	while (DEQUEUED_WAITQ(spipe, sc))
   2455 		slhci_enter_xfer(sc, spipe);
   2456 }
   2457 
   2458 static void
   2459 slhci_queue_timed(struct slhci_softc *sc, struct slhci_pipe *spipe)
   2460 {
   2461 	struct slhci_transfers *t;
   2462 	struct gcq *q;
   2463 	struct slhci_pipe *spp;
   2464 
   2465 	t = &sc->sc_transfers;
   2466 
   2467 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2468 
   2469 	FIND_TIMED(q, t, spp, spp->frame > spipe->frame);
   2470 	gcq_insert_before(q, &spipe->xq);
   2471 }
   2472 
   2473 static void
   2474 slhci_xfer_timer(struct slhci_softc *sc, struct slhci_pipe *spipe)
   2475 {
   2476 	struct slhci_transfers *t;
   2477 	struct gcq *q;
   2478 	struct slhci_pipe *spp;
   2479 
   2480 	t = &sc->sc_transfers;
   2481 
   2482 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2483 
   2484 	FIND_TO(q, t, spp, spp->to_frame >= spipe->to_frame);
   2485 	gcq_insert_before(q, &spipe->to);
   2486 }
   2487 
   2488 static void
   2489 slhci_do_repeat(struct slhci_softc *sc, struct usbd_xfer *xfer)
   2490 {
   2491 	struct slhci_transfers *t;
   2492 	struct slhci_pipe *spipe;
   2493 
   2494 	t = &sc->sc_transfers;
   2495 	spipe = (struct slhci_pipe *)xfer->pipe;
   2496 
   2497 	if (xfer == t->rootintr)
   2498 		return;
   2499 
   2500 	DLOG(D_TRACE, "REPEAT: xfer %p actlen %d frame %u now %u",
   2501 	    xfer, xfer->actlen, spipe->frame, sc->sc_transfers.frame);
   2502 
   2503 	xfer->actlen = 0;
   2504 	spipe->xfer = xfer;
   2505 	if (spipe->tregs[LEN])
   2506 		KASSERT(spipe->buffer == KERNADDR(&xfer->dmabuf, 0));
   2507 	slhci_queue_timed(sc, spipe);
   2508 	slhci_dotransfer(sc);
   2509 }
   2510 
   2511 static void
   2512 slhci_callback_schedule(struct slhci_softc *sc)
   2513 {
   2514 	struct slhci_transfers *t;
   2515 
   2516 	t = &sc->sc_transfers;
   2517 
   2518 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2519 
   2520 	if (t->flags & F_ACTIVE)
   2521 		slhci_do_callback_schedule(sc);
   2522 }
   2523 
   2524 static void
   2525 slhci_do_callback_schedule(struct slhci_softc *sc)
   2526 {
   2527 	struct slhci_transfers *t;
   2528 
   2529 	t = &sc->sc_transfers;
   2530 
   2531 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2532 
   2533 	if (!(t->flags & F_CALLBACK)) {
   2534 		t->flags |= F_CALLBACK;
   2535 		softint_schedule(sc->sc_cb_softintr);
   2536 	}
   2537 }
   2538 
   2539 #if 0
   2540 /* must be called with lock taken from IPL_USB */
   2541 /* XXX static */ void
   2542 slhci_pollxfer(struct slhci_softc *sc, struct usbd_xfer *xfer)
   2543 {
   2544 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2545 	slhci_dotransfer(sc);
   2546 	do {
   2547 		slhci_dointr(sc);
   2548 	} while (xfer->status == USBD_IN_PROGRESS);
   2549 	slhci_do_callback(sc, xfer);
   2550 }
   2551 #endif
   2552 
   2553 static usbd_status
   2554 slhci_do_poll(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
   2555     usbd_xfer *xfer)
   2556 {
   2557 	slhci_waitintr(sc, 0);
   2558 
   2559 	return USBD_NORMAL_COMPLETION;
   2560 }
   2561 
   2562 static usbd_status
   2563 slhci_lsvh_warn(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
   2564     usbd_xfer *xfer)
   2565 {
   2566 	struct slhci_transfers *t;
   2567 
   2568 	t = &sc->sc_transfers;
   2569 
   2570 	if (!(t->flags & F_LSVH_WARNED)) {
   2571 		printf("%s: Low speed device via hub disabled, "
   2572 		    "see slhci(4)\n", SC_NAME(sc));
   2573 		DDOLOG("%s: Low speed device via hub disabled, "
   2574 		    "see slhci(4)\n", SC_NAME(sc), 0,0,0);
   2575 		t->flags |= F_LSVH_WARNED;
   2576 	}
   2577 	return USBD_INVAL;
   2578 }
   2579 
   2580 static usbd_status
   2581 slhci_isoc_warn(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
   2582     usbd_xfer *xfer)
   2583 {
   2584 	struct slhci_transfers *t;
   2585 
   2586 	t = &sc->sc_transfers;
   2587 
   2588 	if (!(t->flags & F_ISOC_WARNED)) {
   2589 		printf("%s: ISOC transfer not supported "
   2590 		    "(see slhci(4))\n", SC_NAME(sc));
   2591 		DDOLOG("%s: ISOC transfer not supported "
   2592 		    "(see slhci(4))\n", SC_NAME(sc), 0,0,0);
   2593 		t->flags |= F_ISOC_WARNED;
   2594 	}
   2595 	return USBD_INVAL;
   2596 }
   2597 
   2598 static usbd_status
   2599 slhci_open_pipe(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
   2600     usbd_xfer *xfer)
   2601 {
   2602 	struct slhci_transfers *t;
   2603 	struct usbd_pipe *pipe;
   2604 
   2605 	t = &sc->sc_transfers;
   2606 	pipe = &spipe->pipe;
   2607 
   2608 	if (t->flags & F_DISABLED)
   2609 		return USBD_CANCELLED;
   2610 	else if (pipe->interval && !slhci_reserve_bustime(sc, spipe, 1))
   2611 		return USBD_PENDING_REQUESTS;
   2612 	else {
   2613 		enter_all_pipes(t, spipe);
   2614 		return USBD_NORMAL_COMPLETION;
   2615 	}
   2616 }
   2617 
   2618 static usbd_status
   2619 slhci_close_pipe(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
   2620     usbd_xfer *xfer)
   2621 {
   2622 	struct usbd_pipe *pipe;
   2623 
   2624 	pipe = &spipe->pipe;
   2625 
   2626 	if (pipe->interval && spipe->ptype != PT_ROOT_INTR)
   2627 		slhci_reserve_bustime(sc, spipe, 0);
   2628 	gcq_remove(&spipe->ap);
   2629 	return USBD_NORMAL_COMPLETION;
   2630 }
   2631 
   2632 static usbd_status
   2633 slhci_do_abort(struct slhci_softc *sc, struct slhci_pipe *spipe, struct
   2634     usbd_xfer *xfer)
   2635 {
   2636 	struct slhci_transfers *t;
   2637 
   2638 	t = &sc->sc_transfers;
   2639 
   2640 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2641 
   2642 	if (spipe->xfer == xfer) {
   2643 		if (spipe->ptype == PT_ROOT_INTR) {
   2644 			if (t->rootintr == spipe->xfer) /* XXX assert? */
   2645 				t->rootintr = NULL;
   2646 		} else {
   2647 			gcq_remove(&spipe->to);
   2648 			gcq_remove(&spipe->xq);
   2649 
   2650 			if (t->spipe[A] == spipe) {
   2651 				t->spipe[A] = NULL;
   2652 				if (!(t->flags & F_AINPROG))
   2653 					t->len[A] = -1;
   2654 			} else if (t->spipe[B] == spipe) {
   2655 					t->spipe[B] = NULL;
   2656 				if (!(t->flags & F_BINPROG))
   2657 					t->len[B] = -1;
   2658 			}
   2659 		}
   2660 
   2661 		if (xfer->status != USBD_TIMEOUT) {
   2662 			spipe->xfer = NULL;
   2663 			spipe->pipe.repeat = 0; /* XXX timeout? */
   2664 		}
   2665 	}
   2666 
   2667 	return USBD_NORMAL_COMPLETION;
   2668 }
   2669 
   2670 /*
   2671  * Called to deactivate or stop use of the controller instead of panicking.
   2672  * Will cancel the xfer correctly even when not on a list.
   2673  */
   2674 static usbd_status
   2675 slhci_halt(struct slhci_softc *sc, struct slhci_pipe *spipe, struct usbd_xfer
   2676     *xfer)
   2677 {
   2678 	struct slhci_transfers *t;
   2679 
   2680 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2681 
   2682 	t = &sc->sc_transfers;
   2683 
   2684 	DDOLOG("Halt! sc %p spipe %p xfer %p", sc, spipe, xfer, 0);
   2685 
   2686 	if (spipe != NULL)
   2687 		slhci_log_spipe(spipe);
   2688 
   2689 	if (xfer != NULL)
   2690 		slhci_log_xfer(xfer);
   2691 
   2692 	if (spipe != NULL && xfer != NULL && spipe->xfer == xfer &&
   2693 	    !gcq_onlist(&spipe->xq) && t->spipe[A] != spipe && t->spipe[B] !=
   2694 	    spipe) {
   2695 		xfer->status = USBD_CANCELLED;
   2696 		enter_callback(t, spipe);
   2697 	}
   2698 
   2699 	if (t->flags & F_ACTIVE) {
   2700 		slhci_intrchange(sc, 0);
   2701 		/*
   2702 		 * leave power on when halting in case flash devices or disks
   2703 		 * are attached, which may be writing and could be damaged
   2704 		 * by abrupt power loss.  The root hub clear power feature
   2705 		 * should still work after halting.
   2706 		 */
   2707 	}
   2708 
   2709 	t->flags &= ~F_ACTIVE;
   2710 	t->flags |= F_UDISABLED;
   2711 	if (!(t->flags & F_NODEV))
   2712 		t->flags |= F_NODEV|F_CCONNECT|F_ROOTINTR;
   2713 	slhci_drain(sc);
   2714 
   2715 	/* One last callback for the drain and device removal. */
   2716 	slhci_do_callback_schedule(sc);
   2717 
   2718 	return USBD_NORMAL_COMPLETION;
   2719 }
   2720 
   2721 /*
   2722  * There are three interrupt states: no interrupts during reset and after
   2723  * device deactivation, INSERT only for no device present but power on, and
   2724  * SOF, INSERT, ADONE, and BDONE when device is present.
   2725  */
   2726 static void
   2727 slhci_intrchange(struct slhci_softc *sc, uint8_t new_ier)
   2728 {
   2729 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2730 	if (sc->sc_ier != new_ier) {
   2731 		sc->sc_ier = new_ier;
   2732 		slhci_write(sc, SL11_IER, new_ier);
   2733 		BSB_SYNC(sc->iot, sc->ioh, sc->pst, sc->psz);
   2734 	}
   2735 }
   2736 
   2737 /*
   2738  * Drain: cancel all pending transfers and put them on the callback list and
   2739  * set the UDISABLED flag.  UDISABLED is cleared only by reset.
   2740  */
   2741 static void
   2742 slhci_drain(struct slhci_softc *sc)
   2743 {
   2744 	struct slhci_transfers *t;
   2745 	struct slhci_pipe *spipe;
   2746 	struct gcq *q;
   2747 	int i;
   2748 
   2749  	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2750 
   2751 	t = &sc->sc_transfers;
   2752 
   2753 	DLOG(D_MSG, "DRAIN flags %#x", t->flags, 0,0,0);
   2754 
   2755 	t->pend = INT_MAX;
   2756 
   2757 	for (i=0; i<=1; i++) {
   2758 		t->len[i] = -1;
   2759 		if (t->spipe[i] != NULL) {
   2760 			enter_callback(t, t->spipe[i]);
   2761 			t->spipe[i] = NULL;
   2762 		}
   2763 	}
   2764 
   2765 	/* Merge the queues into the callback queue. */
   2766 	gcq_merge_tail(&t->q[Q_CALLBACKS], &t->q[Q_CB]);
   2767 	gcq_merge_tail(&t->q[Q_CALLBACKS], &t->q[Q_NEXT_CB]);
   2768 	gcq_merge_tail(&t->q[Q_CALLBACKS], &t->timed);
   2769 
   2770 	/*
   2771 	 * Cancel all pipes.  Note that not all of these may be on the
   2772 	 * callback queue yet; some could be in slhci_start, for example.
   2773 	 */
   2774 	FOREACH_AP(q, t, spipe) {
   2775 		spipe->pflags |= PF_GONE;
   2776 		spipe->pipe.repeat = 0;
   2777 		spipe->pipe.aborting = 1;
   2778 		if (spipe->xfer != NULL)
   2779 			spipe->xfer->status = USBD_CANCELLED;
   2780 	}
   2781 
   2782 	gcq_remove_all(&t->to);
   2783 
   2784 	t->flags |= F_UDISABLED;
   2785 	t->flags &= ~(F_AREADY|F_BREADY|F_AINPROG|F_BINPROG|F_LOWSPEED);
   2786 }
   2787 
   2788 /*
   2789  * RESET: SL11_CTRL_RESETENGINE=1 and SL11_CTRL_JKSTATE=0 for 50ms
   2790  * reconfigure SOF after reset, must wait 2.5us before USB bus activity (SOF)
   2791  * check attached device speed.
   2792  * must wait 100ms before USB transaction according to app note, 10ms
   2793  * by spec.  uhub does this delay
   2794  *
   2795  * Started from root hub set feature reset, which does step one.
   2796  * use_polling will call slhci_reset directly, otherwise the callout goes
   2797  * through slhci_reset_entry.
   2798  */
   2799 void
   2800 slhci_reset(struct slhci_softc *sc)
   2801 {
   2802 	struct slhci_transfers *t;
   2803 	struct slhci_pipe *spipe;
   2804 	struct gcq *q;
   2805 	uint8_t r, pol, ctrl;
   2806 
   2807 	t = &sc->sc_transfers;
   2808 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2809 
   2810 	stop_cc_time(&t_delay);
   2811 
   2812 	KASSERT(t->flags & F_ACTIVE);
   2813 
   2814 	start_cc_time(&t_delay, 0);
   2815 	stop_cc_time(&t_delay);
   2816 
   2817 	slhci_write(sc, SL11_CTRL, 0);
   2818 	start_cc_time(&t_delay, 3);
   2819 	DELAY(3);
   2820 	stop_cc_time(&t_delay);
   2821 	slhci_write(sc, SL11_ISR, 0xff);
   2822 
   2823 	r = slhci_read(sc, SL11_ISR);
   2824 
   2825 	if (r & SL11_ISR_INSERT)
   2826 		slhci_write(sc, SL11_ISR, SL11_ISR_INSERT);
   2827 
   2828 	if (r & SL11_ISR_NODEV) {
   2829 		DLOG(D_MSG, "NC", 0,0,0,0);
   2830 		/*
   2831 		 * Normally, the hard interrupt insert routine will issue
   2832 		 * CCONNECT, however we need to do it here if the detach
   2833 		 * happened during reset.
   2834 		 */
   2835 		if (!(t->flags & F_NODEV))
   2836 			t->flags |= F_CCONNECT|F_ROOTINTR|F_NODEV;
   2837 		slhci_intrchange(sc, SL11_IER_INSERT);
   2838 	} else {
   2839 		if (t->flags & F_NODEV)
   2840 			t->flags |= F_CCONNECT;
   2841 		t->flags &= ~(F_NODEV|F_LOWSPEED);
   2842 		if (r & SL11_ISR_DATA) {
   2843 			DLOG(D_MSG, "FS", 0,0,0,0);
   2844 			pol = ctrl = 0;
   2845 		} else {
   2846 			DLOG(D_MSG, "LS", 0,0,0,0);
   2847 			pol  = SL811_CSOF_POLARITY;
   2848 			ctrl = SL11_CTRL_LOWSPEED;
   2849 			t->flags |= F_LOWSPEED;
   2850 		}
   2851 
   2852 		/* Enable SOF auto-generation */
   2853 		t->frame = 0;	/* write to SL811_CSOF will reset frame */
   2854 		slhci_write(sc, SL11_SOFTIME, 0xe0);
   2855 		slhci_write(sc, SL811_CSOF, pol|SL811_CSOF_MASTER|0x2e);
   2856 		slhci_write(sc, SL11_CTRL, ctrl|SL11_CTRL_ENABLESOF);
   2857 
   2858 		/*
   2859 		 * According to the app note, ARM must be set
   2860 		 * for SOF generation to work.  We initialize all
   2861 		 * USBA registers here for current_tregs.
   2862 		 */
   2863 		slhci_write(sc, SL11_E0ADDR, SL11_BUFFER_START);
   2864 		slhci_write(sc, SL11_E0LEN, 0);
   2865 		slhci_write(sc, SL11_E0PID, SL11_PID_SOF);
   2866 		slhci_write(sc, SL11_E0DEV, 0);
   2867 		slhci_write(sc, SL11_E0CTRL, SL11_EPCTRL_ARM);
   2868 
   2869 		/*
   2870 		 * Initialize B registers.  This can't be done earlier since
   2871 		 * they are not valid until the SL811_CSOF register is written
   2872 		 * above due to SL11H compatability.
   2873 		 */
   2874 		slhci_write(sc, SL11_E1ADDR, SL11_BUFFER_END - 8);
   2875 		slhci_write(sc, SL11_E1LEN, 0);
   2876 		slhci_write(sc, SL11_E1PID, 0);
   2877 		slhci_write(sc, SL11_E1DEV, 0);
   2878 
   2879 		t->current_tregs[0][ADR] = SL11_BUFFER_START;
   2880 		t->current_tregs[0][LEN] = 0;
   2881 		t->current_tregs[0][PID] = SL11_PID_SOF;
   2882 		t->current_tregs[0][DEV] = 0;
   2883 		t->current_tregs[1][ADR] = SL11_BUFFER_END - 8;
   2884 		t->current_tregs[1][LEN] = 0;
   2885 		t->current_tregs[1][PID] = 0;
   2886 		t->current_tregs[1][DEV] = 0;
   2887 
   2888 		/* SOF start will produce USBA interrupt */
   2889 		t->len[A] = 0;
   2890 		t->flags |= F_AINPROG;
   2891 
   2892 		slhci_intrchange(sc, SLHCI_NORMAL_INTERRUPTS);
   2893 	}
   2894 
   2895 	t->flags &= ~(F_UDISABLED|F_RESET);
   2896 	t->flags |= F_CRESET|F_ROOTINTR;
   2897 	FOREACH_AP(q, t, spipe) {
   2898 		spipe->pflags &= ~PF_GONE;
   2899 		spipe->pipe.aborting = 0;
   2900 	}
   2901 	DLOG(D_MSG, "RESET done flags %#x", t->flags, 0,0,0);
   2902 }
   2903 
   2904 /* returns 1 if succeeded, 0 if failed, reserve == 0 is unreserve */
   2905 static int
   2906 slhci_reserve_bustime(struct slhci_softc *sc, struct slhci_pipe *spipe, int
   2907     reserve)
   2908 {
   2909 	struct slhci_transfers *t;
   2910 	int bustime, max_packet;
   2911 
   2912 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2913 
   2914 	t = &sc->sc_transfers;
   2915 	max_packet = UGETW(spipe->pipe.endpoint->edesc->wMaxPacketSize);
   2916 
   2917 	if (spipe->pflags & PF_LS)
   2918 		bustime = SLHCI_LS_CONST + SLHCI_LS_DATA_TIME(max_packet);
   2919 	else
   2920 		bustime = SLHCI_FS_CONST + SLHCI_FS_DATA_TIME(max_packet);
   2921 
   2922 	if (!reserve) {
   2923 		t->reserved_bustime -= bustime;
   2924 #ifdef DIAGNOSTIC
   2925 		if (t->reserved_bustime < 0) {
   2926 			printf("%s: reserved_bustime %d < 0!\n",
   2927 			    SC_NAME(sc), t->reserved_bustime);
   2928 			DDOLOG("%s: reserved_bustime %d < 0!\n",
   2929 			    SC_NAME(sc), t->reserved_bustime, 0,0);
   2930 			t->reserved_bustime = 0;
   2931 		}
   2932 #endif
   2933 		return 1;
   2934 	}
   2935 
   2936 	if (t->reserved_bustime + bustime > SLHCI_RESERVED_BUSTIME) {
   2937 		if (ratecheck(&sc->sc_reserved_warn_rate,
   2938 		    &reserved_warn_rate))
   2939 #ifdef SLHCI_NO_OVERTIME
   2940 		{
   2941 			printf("%s: Max reserved bus time exceeded! "
   2942 			    "Erroring request.\n", SC_NAME(sc));
   2943 			DDOLOG("%s: Max reserved bus time exceeded! "
   2944 			    "Erroring request.\n", SC_NAME(sc), 0,0,0);
   2945 		}
   2946 		return 0;
   2947 #else
   2948 		{
   2949 			printf("%s: Reserved bus time exceeds %d!\n",
   2950 			    SC_NAME(sc), SLHCI_RESERVED_BUSTIME);
   2951 			DDOLOG("%s: Reserved bus time exceeds %d!\n",
   2952 			    SC_NAME(sc), SLHCI_RESERVED_BUSTIME, 0,0);
   2953 		}
   2954 #endif
   2955 	}
   2956 
   2957 	t->reserved_bustime += bustime;
   2958 	return 1;
   2959 }
   2960 
   2961 /* Device insertion/removal interrupt */
   2962 static void
   2963 slhci_insert(struct slhci_softc *sc)
   2964 {
   2965 	struct slhci_transfers *t;
   2966 
   2967 	t = &sc->sc_transfers;
   2968 
   2969 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2970 
   2971 	if (t->flags & F_NODEV)
   2972 		slhci_intrchange(sc, 0);
   2973 	else {
   2974 		slhci_drain(sc);
   2975 		slhci_intrchange(sc, SL11_IER_INSERT);
   2976 	}
   2977 	t->flags ^= F_NODEV;
   2978 	t->flags |= F_ROOTINTR|F_CCONNECT;
   2979 	DLOG(D_MSG, "INSERT intr: flags after %#x", t->flags, 0,0,0);
   2980 }
   2981 
   2982 /*
   2983  * Data structures and routines to emulate the root hub.
   2984  */
   2985 static const usb_device_descriptor_t slhci_devd = {
   2986 	USB_DEVICE_DESCRIPTOR_SIZE,
   2987 	UDESC_DEVICE,		/* type */
   2988 	{0x01, 0x01},		/* USB version */
   2989 	UDCLASS_HUB,		/* class */
   2990 	UDSUBCLASS_HUB,		/* subclass */
   2991 	0,			/* protocol */
   2992 	64,			/* max packet */
   2993 	{USB_VENDOR_SCANLOGIC & 0xff,	/* vendor ID (low)  */
   2994 	 USB_VENDOR_SCANLOGIC >> 8  },	/* vendor ID (high) */
   2995 	{0} /* ? */,		/* product ID */
   2996 	{0},			/* device */
   2997 	1,			/* index to manufacturer */
   2998 	2,			/* index to product */
   2999 	0,			/* index to serial number */
   3000 	1			/* number of configurations */
   3001 };
   3002 
   3003 static const struct slhci_confd_t {
   3004 	const usb_config_descriptor_t confd;
   3005 	const usb_interface_descriptor_t ifcd;
   3006 	const usb_endpoint_descriptor_t endpd;
   3007 } UPACKED slhci_confd = {
   3008 	{ /* Configuration */
   3009 		USB_CONFIG_DESCRIPTOR_SIZE,
   3010 		UDESC_CONFIG,
   3011 		{USB_CONFIG_DESCRIPTOR_SIZE +
   3012 		 USB_INTERFACE_DESCRIPTOR_SIZE +
   3013 		 USB_ENDPOINT_DESCRIPTOR_SIZE},
   3014 		1,			/* number of interfaces */
   3015 		1,			/* configuration value */
   3016 		0,			/* index to configuration */
   3017 		UC_SELF_POWERED,	/* attributes */
   3018 		0			/* max current, filled in later */
   3019 	}, { /* Interface */
   3020 		USB_INTERFACE_DESCRIPTOR_SIZE,
   3021 		UDESC_INTERFACE,
   3022 		0,			/* interface number */
   3023 		0,			/* alternate setting */
   3024 		1,			/* number of endpoint */
   3025 		UICLASS_HUB,		/* class */
   3026 		UISUBCLASS_HUB,		/* subclass */
   3027 		0,			/* protocol */
   3028 		0			/* index to interface */
   3029 	}, { /* Endpoint */
   3030 		USB_ENDPOINT_DESCRIPTOR_SIZE,
   3031 		UDESC_ENDPOINT,
   3032 		UE_DIR_IN | ROOT_INTR_ENDPT,	/* endpoint address */
   3033 		UE_INTERRUPT,			/* attributes */
   3034 		{240, 0},			/* max packet size */
   3035 		255				/* interval */
   3036 	}
   3037 };
   3038 
   3039 static const usb_hub_descriptor_t slhci_hubd = {
   3040 	USB_HUB_DESCRIPTOR_SIZE,
   3041 	UDESC_HUB,
   3042 	1,			/* number of ports */
   3043 	{UHD_PWR_INDIVIDUAL | UHD_OC_NONE, 0},	/* hub characteristics */
   3044 	50,			/* 5:power on to power good, units of 2ms */
   3045 	0,			/* 6:maximum current, filled in later */
   3046 	{ 0x00 },		/* port is removable */
   3047 	{ 0x00 }		/* port power control mask */
   3048 };
   3049 
   3050 static usbd_status
   3051 slhci_clear_feature(struct slhci_softc *sc, unsigned int what)
   3052 {
   3053 	struct slhci_transfers *t;
   3054 	usbd_status error;
   3055 
   3056 	t = &sc->sc_transfers;
   3057 	error = USBD_NORMAL_COMPLETION;
   3058 
   3059 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   3060 
   3061 	if (what == UHF_PORT_POWER) {
   3062 		DLOG(D_MSG, "POWER_OFF", 0,0,0,0);
   3063 		t->flags &= ~F_POWER;
   3064 		if (!(t->flags & F_NODEV))
   3065 			t->flags |= F_NODEV|F_CCONNECT|F_ROOTINTR;
   3066 		/* for x68k Nereid USB controller */
   3067 		if (sc->sc_enable_power && (t->flags & F_REALPOWER)) {
   3068 			t->flags &= ~F_REALPOWER;
   3069 			sc->sc_enable_power(sc, POWER_OFF);
   3070 		}
   3071 		slhci_intrchange(sc, 0);
   3072 		slhci_drain(sc);
   3073 	} else if (what == UHF_C_PORT_CONNECTION) {
   3074 		t->flags &= ~F_CCONNECT;
   3075 	} else if (what == UHF_C_PORT_RESET) {
   3076 		t->flags &= ~F_CRESET;
   3077 	} else if (what == UHF_PORT_ENABLE) {
   3078 		slhci_drain(sc);
   3079 	} else if (what != UHF_PORT_SUSPEND) {
   3080 		DDOLOG("ClrPortFeatERR:value=%#.4x", what, 0,0,0);
   3081 		error = USBD_IOERROR;
   3082 	}
   3083 
   3084 	return error;
   3085 }
   3086 
   3087 static usbd_status
   3088 slhci_set_feature(struct slhci_softc *sc, unsigned int what)
   3089 {
   3090 	struct slhci_transfers *t;
   3091 	uint8_t r;
   3092 
   3093 	t = &sc->sc_transfers;
   3094 
   3095 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   3096 
   3097 	if (what == UHF_PORT_RESET) {
   3098 		if (!(t->flags & F_ACTIVE)) {
   3099 			DDOLOG("SET PORT_RESET when not ACTIVE!",
   3100 			    0,0,0,0);
   3101 			return USBD_INVAL;
   3102 		}
   3103 		if (!(t->flags & F_POWER)) {
   3104 			DDOLOG("SET PORT_RESET without PORT_POWER! flags %p",
   3105 			    t->flags, 0,0,0);
   3106 			return USBD_INVAL;
   3107 		}
   3108 		if (t->flags & F_RESET)
   3109 			return USBD_NORMAL_COMPLETION;
   3110 		DLOG(D_MSG, "RESET flags %#x", t->flags, 0,0,0);
   3111 		slhci_intrchange(sc, 0);
   3112 		slhci_drain(sc);
   3113 		slhci_write(sc, SL11_CTRL, SL11_CTRL_RESETENGINE);
   3114 		/* usb spec says delay >= 10ms, app note 50ms */
   3115  		start_cc_time(&t_delay, 50000);
   3116 		if (sc->sc_bus.use_polling) {
   3117 			DELAY(50000);
   3118 			slhci_reset(sc);
   3119 		} else {
   3120 			t->flags |= F_RESET;
   3121 			callout_schedule(&sc->sc_timer, max(mstohz(50), 2));
   3122 		}
   3123 	} else if (what == UHF_PORT_SUSPEND) {
   3124 		printf("%s: USB Suspend not implemented!\n", SC_NAME(sc));
   3125 		DDOLOG("%s: USB Suspend not implemented!\n", SC_NAME(sc),
   3126 		    0,0,0);
   3127 	} else if (what == UHF_PORT_POWER) {
   3128 		DLOG(D_MSG, "PORT_POWER", 0,0,0,0);
   3129 		/* for x68k Nereid USB controller */
   3130 		if (!(t->flags & F_ACTIVE))
   3131 			return USBD_INVAL;
   3132 		if (t->flags & F_POWER)
   3133 			return USBD_NORMAL_COMPLETION;
   3134 		if (!(t->flags & F_REALPOWER)) {
   3135 			if (sc->sc_enable_power)
   3136 				sc->sc_enable_power(sc, POWER_ON);
   3137 			t->flags |= F_REALPOWER;
   3138 		}
   3139 		t->flags |= F_POWER;
   3140 		r = slhci_read(sc, SL11_ISR);
   3141 		if (r & SL11_ISR_INSERT)
   3142 			slhci_write(sc, SL11_ISR, SL11_ISR_INSERT);
   3143 		if (r & SL11_ISR_NODEV) {
   3144 			slhci_intrchange(sc, SL11_IER_INSERT);
   3145 			t->flags |= F_NODEV;
   3146 		} else {
   3147 			t->flags &= ~F_NODEV;
   3148 			t->flags |= F_CCONNECT|F_ROOTINTR;
   3149 		}
   3150 	} else {
   3151 		DDOLOG("SetPortFeatERR=%#.8x", what, 0,0,0);
   3152 		return USBD_IOERROR;
   3153 	}
   3154 
   3155 	return USBD_NORMAL_COMPLETION;
   3156 }
   3157 
   3158 static void
   3159 slhci_get_status(struct slhci_softc *sc, usb_port_status_t *ps)
   3160 {
   3161 	struct slhci_transfers *t;
   3162 	unsigned int status, change;
   3163 
   3164 	t = &sc->sc_transfers;
   3165 
   3166 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   3167 
   3168 	/*
   3169 	 * We do not have a way to detect over current or bable and
   3170 	 * suspend is currently not implemented, so connect and reset
   3171 	 * are the only changes that need to be reported.
   3172 	 */
   3173 	change = 0;
   3174 	if (t->flags & F_CCONNECT)
   3175 		change |= UPS_C_CONNECT_STATUS;
   3176 	if (t->flags & F_CRESET)
   3177 		change |= UPS_C_PORT_RESET;
   3178 
   3179 	status = 0;
   3180 	if (!(t->flags & F_NODEV))
   3181 		status |= UPS_CURRENT_CONNECT_STATUS;
   3182 	if (!(t->flags & F_UDISABLED))
   3183 		status |= UPS_PORT_ENABLED;
   3184 	if (t->flags & F_RESET)
   3185 		status |= UPS_RESET;
   3186 	if (t->flags & F_POWER)
   3187 		status |= UPS_PORT_POWER;
   3188 	if (t->flags & F_LOWSPEED)
   3189 		status |= UPS_LOW_SPEED;
   3190 	USETW(ps->wPortStatus, status);
   3191 	USETW(ps->wPortChange, change);
   3192 	DLOG(D_ROOT, "status=%#.4x, change=%#.4x", status, change, 0,0);
   3193 }
   3194 
   3195 static usbd_status
   3196 slhci_root(struct slhci_softc *sc, struct slhci_pipe *spipe, struct usbd_xfer
   3197     *xfer)
   3198 {
   3199 	struct slhci_transfers *t;
   3200 	usb_device_request_t *req;
   3201 	unsigned int len, value, index, actlen, type;
   3202 	uint8_t *buf;
   3203 	usbd_status error;
   3204 
   3205 	t = &sc->sc_transfers;
   3206 	buf = NULL;
   3207 
   3208 	LK_SLASSERT(spipe != NULL && xfer != NULL, sc, spipe, xfer, return
   3209 	    USBD_CANCELLED);
   3210 
   3211 	DLOG(D_TRACE, "%s start", pnames(SLHCI_XFER_TYPE(xfer)), 0,0,0);
   3212 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   3213 
   3214 	if (spipe->ptype == PT_ROOT_INTR) {
   3215 		LK_SLASSERT(t->rootintr == NULL, sc, spipe, xfer, return
   3216 		    USBD_CANCELLED);
   3217 		t->rootintr = xfer;
   3218 		if (t->flags & F_CHANGE)
   3219 			t->flags |= F_ROOTINTR;
   3220 		return USBD_IN_PROGRESS;
   3221 	}
   3222 
   3223 	error = USBD_IOERROR; /* XXX should be STALL */
   3224 	actlen = 0;
   3225 	req = &xfer->request;
   3226 
   3227 	len = UGETW(req->wLength);
   3228 	value = UGETW(req->wValue);
   3229 	index = UGETW(req->wIndex);
   3230 
   3231 	type = req->bmRequestType;
   3232 
   3233 	if (len)
   3234 		buf = KERNADDR(&xfer->dmabuf, 0);
   3235 
   3236 	SLHCI_DEXEC(D_TRACE, slhci_log_req_hub(req));
   3237 
   3238 	/*
   3239 	 * USB requests for hubs have two basic types, standard and class.
   3240 	 * Each could potentially have recipients of device, interface,
   3241 	 * endpoint, or other.  For the hub class, CLASS_OTHER means the port
   3242 	 * and CLASS_DEVICE means the hub.  For standard requests, OTHER
   3243 	 * is not used.  Standard request are described in section 9.4 of the
   3244 	 * standard, hub class requests in 11.16.  Each request is either read
   3245 	 * or write.
   3246 	 *
   3247 	 * Clear Feature, Set Feature, and Status are defined for each of the
   3248 	 * used recipients.  Get Descriptor and Set Descriptor are defined for
   3249 	 * both standard and hub class types with different descriptors.
   3250 	 * Other requests have only one defined recipient and type.  These
   3251 	 * include: Get/Set Address, Get/Set Configuration, Get/Set Interface,
   3252 	 * and Synch Frame for standard requests and Get Bus State for hub
   3253 	 * class.
   3254 	 *
   3255 	 * When a device is first powered up it has address 0 until the
   3256 	 * address is set.
   3257 	 *
   3258 	 * Hubs are only allowed to support one interface and may not have
   3259 	 * isochronous endpoints.  The results of the related requests are
   3260 	 * undefined.
   3261 	 *
   3262 	 * The standard requires invalid or unsupported requests to return
   3263 	 * STALL in the data stage, however this does not work well with
   3264 	 * current error handling. XXX
   3265 	 *
   3266 	 * Some unsupported fields:
   3267 	 * Clear Hub Feature is for C_HUB_LOCAL_POWER and C_HUB_OVER_CURRENT
   3268 	 * Set Device Features is for ENDPOINT_HALT and DEVICE_REMOTE_WAKEUP
   3269 	 * Get Bus State is optional sample of D- and D+ at EOF2
   3270 	 */
   3271 
   3272 	switch (req->bRequest) {
   3273 	/* Write Requests */
   3274 	case UR_CLEAR_FEATURE:
   3275 		if (type == UT_WRITE_CLASS_OTHER) {
   3276 			if (index == 1 /* Port */)
   3277 				error = slhci_clear_feature(sc, value);
   3278 			else
   3279 				DLOG(D_ROOT, "Clear Port Feature "
   3280 				    "index = %#.4x", index, 0,0,0);
   3281 		}
   3282 		break;
   3283 	case UR_SET_FEATURE:
   3284 		if (type == UT_WRITE_CLASS_OTHER) {
   3285 			if (index == 1 /* Port */)
   3286 				error = slhci_set_feature(sc, value);
   3287 			else
   3288 				DLOG(D_ROOT, "Set Port Feature "
   3289 				    "index = %#.4x", index, 0,0,0);
   3290 		} else if (type != UT_WRITE_CLASS_DEVICE)
   3291 			DLOG(D_ROOT, "Set Device Feature "
   3292 			    "ENDPOINT_HALT or DEVICE_REMOTE_WAKEUP "
   3293 			    "not supported", 0,0,0,0);
   3294 		break;
   3295 	case UR_SET_ADDRESS:
   3296 		if (type == UT_WRITE_DEVICE) {
   3297 			DLOG(D_ROOT, "Set Address %#.4x", value, 0,0,0);
   3298 			if (value < USB_MAX_DEVICES) {
   3299 				t->rootaddr = value;
   3300 				error = USBD_NORMAL_COMPLETION;
   3301 			}
   3302 		}
   3303 		break;
   3304 	case UR_SET_CONFIG:
   3305 		if (type == UT_WRITE_DEVICE) {
   3306 			DLOG(D_ROOT, "Set Config %#.4x", value, 0,0,0);
   3307 			if (value == 0 || value == 1) {
   3308 				t->rootconf = value;
   3309 				error = USBD_NORMAL_COMPLETION;
   3310 			}
   3311 		}
   3312 		break;
   3313 	/* Read Requests */
   3314 	case UR_GET_STATUS:
   3315 		if (type == UT_READ_CLASS_OTHER) {
   3316 			if (index == 1 /* Port */ && len == /* XXX >=? */
   3317 			    sizeof(usb_port_status_t)) {
   3318 				slhci_get_status(sc, (usb_port_status_t *)
   3319 				    buf);
   3320 				actlen = sizeof(usb_port_status_t);
   3321 				error = USBD_NORMAL_COMPLETION;
   3322 			} else
   3323 				DLOG(D_ROOT, "Get Port Status index = %#.4x "
   3324 				    "len = %#.4x", index, len, 0,0);
   3325 		} else if (type == UT_READ_CLASS_DEVICE) { /* XXX index? */
   3326 			if (len == sizeof(usb_hub_status_t)) {
   3327 				DLOG(D_ROOT, "Get Hub Status",
   3328 				    0,0,0,0);
   3329 				actlen = sizeof(usb_hub_status_t);
   3330 				memset(buf, 0, actlen);
   3331 				error = USBD_NORMAL_COMPLETION;
   3332 			} else
   3333 				DLOG(D_ROOT, "Get Hub Status bad len %#.4x",
   3334 				    len, 0,0,0);
   3335 		} else if (type == UT_READ_DEVICE) {
   3336 			if (len >= 2) {
   3337 				USETW(((usb_status_t *)buf)->wStatus, UDS_SELF_POWERED);
   3338 				actlen = 2;
   3339 				error = USBD_NORMAL_COMPLETION;
   3340 			}
   3341 		} else if (type == (UT_READ_INTERFACE|UT_READ_ENDPOINT)) {
   3342 			if (len >= 2) {
   3343 				USETW(((usb_status_t *)buf)->wStatus, 0);
   3344 				actlen = 2;
   3345 				error = USBD_NORMAL_COMPLETION;
   3346 			}
   3347 		}
   3348 		break;
   3349 	case UR_GET_CONFIG:
   3350 		if (type == UT_READ_DEVICE) {
   3351 			DLOG(D_ROOT, "Get Config", 0,0,0,0);
   3352 			if (len > 0) {
   3353 				*buf = t->rootconf;
   3354 				actlen = 1;
   3355 				error = USBD_NORMAL_COMPLETION;
   3356 			}
   3357 		}
   3358 		break;
   3359 	case UR_GET_INTERFACE:
   3360 		if (type == UT_READ_INTERFACE) {
   3361 			if (len > 0) {
   3362 				*buf = 0;
   3363 				actlen = 1;
   3364 				error = USBD_NORMAL_COMPLETION;
   3365 			}
   3366 		}
   3367 		break;
   3368 	case UR_GET_DESCRIPTOR:
   3369 		if (type == UT_READ_DEVICE) {
   3370 			/* value is type (&0xff00) and index (0xff) */
   3371 			if (value == (UDESC_DEVICE<<8)) {
   3372 				actlen = min(len, sizeof(slhci_devd));
   3373 				memcpy(buf, &slhci_devd, actlen);
   3374 				error = USBD_NORMAL_COMPLETION;
   3375 			} else if (value == (UDESC_CONFIG<<8)) {
   3376 				actlen = min(len, sizeof(slhci_confd));
   3377 				memcpy(buf, &slhci_confd, actlen);
   3378 				if (actlen > offsetof(usb_config_descriptor_t,
   3379 				    bMaxPower))
   3380 					((usb_config_descriptor_t *)
   3381 					    buf)->bMaxPower = t->max_current;
   3382 					    /* 2 mA units */
   3383 				error = USBD_NORMAL_COMPLETION;
   3384 			} else if (value == (UDESC_STRING<<8)) {
   3385 				/* language table XXX */
   3386 			} else if (value == ((UDESC_STRING<<8)|1)) {
   3387 				/* Vendor */
   3388 				actlen = usb_makestrdesc((usb_string_descriptor_t *)
   3389 				    buf, len, "ScanLogic/Cypress");
   3390 				error = USBD_NORMAL_COMPLETION;
   3391 			} else if (value == ((UDESC_STRING<<8)|2)) {
   3392 				/* Product */
   3393 				actlen = usb_makestrdesc((usb_string_descriptor_t *)
   3394 				    buf, len, "SL811HS/T root hub");
   3395 				error = USBD_NORMAL_COMPLETION;
   3396 			} else
   3397 				DDOLOG("Unknown Get Descriptor %#.4x",
   3398 				    value, 0,0,0);
   3399 		} else if (type == UT_READ_CLASS_DEVICE) {
   3400 			/* Descriptor number is 0 */
   3401 			if (value == (UDESC_HUB<<8)) {
   3402 				actlen = min(len, sizeof(slhci_hubd));
   3403 				memcpy(buf, &slhci_hubd, actlen);
   3404 				if (actlen > offsetof(usb_config_descriptor_t,
   3405 				    bMaxPower))
   3406 					((usb_hub_descriptor_t *)
   3407 					    buf)->bHubContrCurrent = 500 -
   3408 					    t->max_current;
   3409 				error = USBD_NORMAL_COMPLETION;
   3410 			} else
   3411 				DDOLOG("Unknown Get Hub Descriptor %#.4x",
   3412 				    value, 0,0,0);
   3413 		}
   3414 		break;
   3415 	}
   3416 
   3417 	if (error == USBD_NORMAL_COMPLETION)
   3418 		xfer->actlen = actlen;
   3419 	xfer->status = error;
   3420 	KASSERT(spipe->xfer == NULL);
   3421 	spipe->xfer = xfer;
   3422 	enter_callback(t, spipe);
   3423 
   3424 	return USBD_IN_PROGRESS;
   3425 }
   3426 
   3427 /* End in lock functions. Start debug functions. */
   3428 
   3429 #ifdef SLHCI_DEBUG
   3430 void
   3431 slhci_log_buffer(struct usbd_xfer *xfer)
   3432 {
   3433 	u_char *buf;
   3434 
   3435 	if(xfer->length > 0 &&
   3436 	    UE_GET_DIR(xfer->pipe->endpoint->edesc->bEndpointAddress) ==
   3437 	    UE_DIR_IN) {
   3438 		buf = KERNADDR(&xfer->dmabuf, 0);
   3439 		DDOLOGBUF(buf, xfer->actlen);
   3440 		DDOLOG("len %d actlen %d short %d", xfer->length,
   3441 		    xfer->actlen, xfer->length - xfer->actlen, 0);
   3442 	}
   3443 }
   3444 
   3445 void
   3446 slhci_log_req(usb_device_request_t *r)
   3447 {
   3448 	static const char *xmes[]={
   3449 		"GETSTAT",
   3450 		"CLRFEAT",
   3451 		"res",
   3452 		"SETFEAT",
   3453 		"res",
   3454 		"SETADDR",
   3455 		"GETDESC",
   3456 		"SETDESC",
   3457 		"GETCONF",
   3458 		"SETCONF",
   3459 		"GETIN/F",
   3460 		"SETIN/F",
   3461 		"SYNC_FR",
   3462 		"UNKNOWN"
   3463 	};
   3464 	int req, mreq, type, value, index, len;
   3465 
   3466 	req   = r->bRequest;
   3467 	mreq  = (req > 13) ? 13 : req;
   3468 	type  = r->bmRequestType;
   3469 	value = UGETW(r->wValue);
   3470 	index = UGETW(r->wIndex);
   3471 	len   = UGETW(r->wLength);
   3472 
   3473 	DDOLOG("request: %s %#x", xmes[mreq], type, 0,0);
   3474 	DDOLOG("request: r=%d,v=%d,i=%d,l=%d ", req, value, index, len);
   3475 }
   3476 
   3477 void
   3478 slhci_log_req_hub(usb_device_request_t *r)
   3479 {
   3480 	static const struct {
   3481 		int req;
   3482 		int type;
   3483 		const char *str;
   3484 	} conf[] = {
   3485 		{ 1, 0x20, "ClrHubFeat"  },
   3486 		{ 1, 0x23, "ClrPortFeat" },
   3487 		{ 2, 0xa3, "GetBusState" },
   3488 		{ 6, 0xa0, "GetHubDesc"  },
   3489 		{ 0, 0xa0, "GetHubStat"  },
   3490 		{ 0, 0xa3, "GetPortStat" },
   3491 		{ 7, 0x20, "SetHubDesc"  },
   3492 		{ 3, 0x20, "SetHubFeat"  },
   3493 		{ 3, 0x23, "SetPortFeat" },
   3494 		{-1, 0, NULL},
   3495 	};
   3496 	int i;
   3497 	int value, index, len;
   3498 	const char *str;
   3499 
   3500 	value = UGETW(r->wValue);
   3501 	index = UGETW(r->wIndex);
   3502 	len   = UGETW(r->wLength);
   3503 	for (i = 0; ; i++) {
   3504 		if (conf[i].req == -1 ) {
   3505 			slhci_log_req(r);
   3506 			return;
   3507 		}
   3508 		if (r->bmRequestType == conf[i].type && r->bRequest == conf[i].req) {
   3509 			str = conf[i].str;
   3510 			break;
   3511 		}
   3512 	}
   3513 	DDOLOG("hub request: %s v=%d,i=%d,l=%d ", str, value, index, len);
   3514 }
   3515 
   3516 void
   3517 slhci_log_dumpreg(void)
   3518 {
   3519 	uint8_t r;
   3520 	unsigned int aaddr, alen, baddr, blen;
   3521 	static u_char buf[240];
   3522 
   3523 	r = slhci_read(ssc, SL11_E0CTRL);
   3524 	DDOLOG("USB A Host Control = %#.2x", r, 0,0,0);
   3525 	DDOLOGFLAG8("E0CTRL=", r, "Preamble", "Data Toggle",  "SOF Sync",
   3526 	    "ISOC", "res", "Out", "Enable", "Arm");
   3527 	aaddr = slhci_read(ssc, SL11_E0ADDR);
   3528 	DDOLOG("USB A Base Address = %u", aaddr, 0,0,0);
   3529 	alen = slhci_read(ssc, SL11_E0LEN);
   3530 	DDOLOG("USB A Length = %u", alen, 0,0,0);
   3531 	r = slhci_read(ssc, SL11_E0STAT);
   3532 	DDOLOG("USB A Status = %#.2x", r, 0,0,0);
   3533 	DDOLOGFLAG8("E0STAT=", r, "STALL", "NAK", "Overflow", "Setup",
   3534 	    "Data Toggle", "Timeout", "Error", "ACK");
   3535 	r = slhci_read(ssc, SL11_E0CONT);
   3536 	DDOLOG("USB A Remaining or Overflow Length = %u", r, 0,0,0);
   3537 	r = slhci_read(ssc, SL11_E1CTRL);
   3538 	DDOLOG("USB B Host Control = %#.2x", r, 0,0,0);
   3539 	DDOLOGFLAG8("E1CTRL=", r, "Preamble", "Data Toggle",  "SOF Sync",
   3540 	    "ISOC", "res", "Out", "Enable", "Arm");
   3541 	baddr = slhci_read(ssc, SL11_E1ADDR);
   3542 	DDOLOG("USB B Base Address = %u", baddr, 0,0,0);
   3543 	blen = slhci_read(ssc, SL11_E1LEN);
   3544 	DDOLOG("USB B Length = %u", blen, 0,0,0);
   3545 	r = slhci_read(ssc, SL11_E1STAT);
   3546 	DDOLOG("USB B Status = %#.2x", r, 0,0,0);
   3547 	DDOLOGFLAG8("E1STAT=", r, "STALL", "NAK", "Overflow", "Setup",
   3548 	    "Data Toggle", "Timeout", "Error", "ACK");
   3549 	r = slhci_read(ssc, SL11_E1CONT);
   3550 	DDOLOG("USB B Remaining or Overflow Length = %u", r, 0,0,0);
   3551 
   3552 	r = slhci_read(ssc, SL11_CTRL);
   3553 	DDOLOG("Control = %#.2x", r, 0,0,0);
   3554 	DDOLOGFLAG8("CTRL=", r, "res", "Suspend", "LOW Speed",
   3555 	    "J-K State Force", "Reset", "res", "res", "SOF");
   3556 	r = slhci_read(ssc, SL11_IER);
   3557 	DDOLOG("Interrupt Enable = %#.2x", r, 0,0,0);
   3558 	DDOLOGFLAG8("IER=", r, "D+ **IER!**", "Device Detect/Resume",
   3559 	    "Insert/Remove", "SOF", "res", "res", "USBB", "USBA");
   3560 	r = slhci_read(ssc, SL11_ISR);
   3561 	DDOLOG("Interrupt Status = %#.2x", r, 0,0,0);
   3562 	DDOLOGFLAG8("ISR=", r, "D+", "Device Detect/Resume",
   3563 	    "Insert/Remove", "SOF", "res", "res", "USBB", "USBA");
   3564 	r = slhci_read(ssc, SL11_REV);
   3565 	DDOLOG("Revision = %#.2x", r, 0,0,0);
   3566 	r = slhci_read(ssc, SL811_CSOF);
   3567 	DDOLOG("SOF Counter = %#.2x", r, 0,0,0);
   3568 
   3569 	if (alen && aaddr >= SL11_BUFFER_START && aaddr < SL11_BUFFER_END &&
   3570 	    alen <= SL11_MAX_PACKET_SIZE && aaddr + alen <= SL11_BUFFER_END) {
   3571 		slhci_read_multi(ssc, aaddr, buf, alen);
   3572 		DDOLOG("USBA Buffer: start %u len %u", aaddr, alen, 0,0);
   3573 		DDOLOGBUF(buf, alen);
   3574 	} else if (alen)
   3575 		DDOLOG("USBA Buffer Invalid", 0,0,0,0);
   3576 
   3577 	if (blen && baddr >= SL11_BUFFER_START && baddr < SL11_BUFFER_END &&
   3578 	    blen <= SL11_MAX_PACKET_SIZE && baddr + blen <= SL11_BUFFER_END) {
   3579 		slhci_read_multi(ssc, baddr, buf, blen);
   3580 		DDOLOG("USBB Buffer: start %u len %u", baddr, blen, 0,0);
   3581 		DDOLOGBUF(buf, blen);
   3582 	} else if (blen)
   3583 		DDOLOG("USBB Buffer Invalid", 0,0,0,0);
   3584 }
   3585 
   3586 void
   3587 slhci_log_xfer(struct usbd_xfer *xfer)
   3588 {
   3589 	DDOLOG("xfer: length=%u, actlen=%u, flags=%#x, timeout=%u,",
   3590 		xfer->length, xfer->actlen, xfer->flags, xfer->timeout);
   3591 	if (xfer->dmabuf.block)
   3592 		DDOLOG("buffer=%p", KERNADDR(&xfer->dmabuf, 0), 0,0,0);
   3593 	slhci_log_req_hub(&xfer->request);
   3594 }
   3595 
   3596 void
   3597 slhci_log_spipe(struct slhci_pipe *spipe)
   3598 {
   3599 	DDOLOG("spipe %p onlists: %s %s %s", spipe, gcq_onlist(&spipe->ap) ?
   3600 	    "AP" : "", gcq_onlist(&spipe->to) ? "TO" : "",
   3601 	    gcq_onlist(&spipe->xq) ? "XQ" : "");
   3602 	DDOLOG("spipe: xfer %p buffer %p pflags %#x ptype %s",
   3603 	    spipe->xfer, spipe->buffer, spipe->pflags, pnames(spipe->ptype));
   3604 }
   3605 
   3606 void
   3607 slhci_print_intr(void)
   3608 {
   3609 	unsigned int ier, isr;
   3610 	ier = slhci_read(ssc, SL11_IER);
   3611 	isr = slhci_read(ssc, SL11_ISR);
   3612 	printf("IER: %#x ISR: %#x \n", ier, isr);
   3613 }
   3614 
   3615 #if 0
   3616 void
   3617 slhci_log_sc(void)
   3618 {
   3619 	struct slhci_transfers *t;
   3620 	int i;
   3621 
   3622 	t = &ssc->sc_transfers;
   3623 
   3624 	DDOLOG("Flags=%#x", t->flags, 0,0,0);
   3625 	DDOLOG("a = %p Alen=%d b = %p Blen=%d", t->spipe[0], t->len[0],
   3626 	    t->spipe[1], t->len[1]);
   3627 
   3628 	for (i=0; i<=Q_MAX; i++)
   3629 		DDOLOG("Q %d: %p", i, gcq_first(&t->q[i]), 0,0);
   3630 
   3631 	DDOLOG("TIMED: %p", GCQ_ITEM(gcq_first(&t->to),
   3632 	    struct slhci_pipe, to), 0,0,0);
   3633 
   3634 	DDOLOG("frame=%d rootintr=%p", t->frame, t->rootintr, 0,0);
   3635 
   3636 	DDOLOG("use_polling=%d", ssc->sc_bus.use_polling, 0, 0, 0);
   3637 }
   3638 
   3639 void
   3640 slhci_log_slreq(struct slhci_pipe *r)
   3641 {
   3642 	DDOLOG("next: %p", r->q.next.sqe_next, 0,0,0);
   3643 	DDOLOG("xfer: %p", r->xfer, 0,0,0);
   3644 	DDOLOG("buffer: %p", r->buffer, 0,0,0);
   3645 	DDOLOG("bustime: %u", r->bustime, 0,0,0);
   3646 	DDOLOG("control: %#x", r->control, 0,0,0);
   3647 	DDOLOGFLAG8("control=", r->control, "Preamble", "Data Toggle",
   3648 	    "SOF Sync", "ISOC", "res", "Out", "Enable", "Arm");
   3649 	DDOLOG("pid: %#x", r->tregs[PID], 0,0,0);
   3650 	DDOLOG("dev: %u", r->tregs[DEV], 0,0,0);
   3651 	DDOLOG("len: %u", r->tregs[LEN], 0,0,0);
   3652 
   3653 	if (r->xfer)
   3654 		slhci_log_xfer(r->xfer);
   3655 }
   3656 #endif
   3657 #endif /* SLHCI_DEBUG */
   3658 /* End debug functions. */
   3659