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