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