Home | History | Annotate | Line # | Download | only in usb
usbdi.c revision 1.212
      1 /*	$NetBSD: usbdi.c,v 1.212 2021/06/12 15:39:57 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998, 2012, 2015 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Lennart Augustsson (lennart (at) augustsson.net) at
      9  * Carlstedt Research & Technology, Matthew R. Green (mrg (at) eterna.com.au),
     10  * and Nick Hudson.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     31  * POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: usbdi.c,v 1.212 2021/06/12 15:39:57 riastradh Exp $");
     36 
     37 #ifdef _KERNEL_OPT
     38 #include "opt_usb.h"
     39 #include "opt_compat_netbsd.h"
     40 #include "usb_dma.h"
     41 #endif
     42 
     43 #include <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/kernel.h>
     46 #include <sys/device.h>
     47 #include <sys/kmem.h>
     48 #include <sys/proc.h>
     49 #include <sys/bus.h>
     50 #include <sys/cpu.h>
     51 
     52 #include <dev/usb/usb.h>
     53 #include <dev/usb/usbdi.h>
     54 #include <dev/usb/usbdi_util.h>
     55 #include <dev/usb/usbdivar.h>
     56 #include <dev/usb/usb_mem.h>
     57 #include <dev/usb/usb_quirks.h>
     58 #include <dev/usb/usb_sdt.h>
     59 #include <dev/usb/usbhist.h>
     60 
     61 /* UTF-8 encoding stuff */
     62 #include <fs/unicode.h>
     63 
     64 extern int usbdebug;
     65 
     66 SDT_PROBE_DEFINE5(usb, device, pipe, open,
     67     "struct usbd_interface *"/*iface*/,
     68     "uint8_t"/*address*/,
     69     "uint8_t"/*flags*/,
     70     "int"/*ival*/,
     71     "struct usbd_pipe *"/*pipe*/);
     72 
     73 SDT_PROBE_DEFINE7(usb, device, pipe, open__intr,
     74     "struct usbd_interface *"/*iface*/,
     75     "uint8_t"/*address*/,
     76     "uint8_t"/*flags*/,
     77     "int"/*ival*/,
     78     "usbd_callback"/*cb*/,
     79     "void *"/*cookie*/,
     80     "struct usbd_pipe *"/*pipe*/);
     81 
     82 SDT_PROBE_DEFINE2(usb, device, pipe, transfer__start,
     83     "struct usbd_pipe *"/*pipe*/,
     84     "struct usbd_xfer *"/*xfer*/);
     85 SDT_PROBE_DEFINE3(usb, device, pipe, transfer__done,
     86     "struct usbd_pipe *"/*pipe*/,
     87     "struct usbd_xfer *"/*xfer*/,
     88     "usbd_status"/*err*/);
     89 SDT_PROBE_DEFINE2(usb, device, pipe, start,
     90     "struct usbd_pipe *"/*pipe*/,
     91     "struct usbd_xfer *"/*xfer*/);
     92 
     93 SDT_PROBE_DEFINE1(usb, device, pipe, close,  "struct usbd_pipe *"/*pipe*/);
     94 SDT_PROBE_DEFINE1(usb, device, pipe, abort__start,
     95     "struct usbd_pipe *"/*pipe*/);
     96 SDT_PROBE_DEFINE1(usb, device, pipe, abort__done,
     97     "struct usbd_pipe *"/*pipe*/);
     98 SDT_PROBE_DEFINE1(usb, device, pipe, clear__endpoint__stall,
     99     "struct usbd_pipe *"/*pipe*/);
    100 SDT_PROBE_DEFINE1(usb, device, pipe, clear__endpoint__toggle,
    101     "struct usbd_pipe *"/*pipe*/);
    102 
    103 SDT_PROBE_DEFINE5(usb, device, xfer, create,
    104     "struct usbd_xfer *"/*xfer*/,
    105     "struct usbd_pipe *"/*pipe*/,
    106     "size_t"/*len*/,
    107     "unsigned int"/*flags*/,
    108     "unsigned int"/*nframes*/);
    109 SDT_PROBE_DEFINE1(usb, device, xfer, start,  "struct usbd_xfer *"/*xfer*/);
    110 SDT_PROBE_DEFINE1(usb, device, xfer, preabort,  "struct usbd_xfer *"/*xfer*/);
    111 SDT_PROBE_DEFINE1(usb, device, xfer, abort,  "struct usbd_xfer *"/*xfer*/);
    112 SDT_PROBE_DEFINE1(usb, device, xfer, timeout,  "struct usbd_xfer *"/*xfer*/);
    113 SDT_PROBE_DEFINE2(usb, device, xfer, done,
    114     "struct usbd_xfer *"/*xfer*/,
    115     "usbd_status"/*status*/);
    116 SDT_PROBE_DEFINE1(usb, device, xfer, destroy,  "struct usbd_xfer *"/*xfer*/);
    117 
    118 Static usbd_status usbd_ar_pipe(struct usbd_pipe *);
    119 Static void usbd_start_next(struct usbd_pipe *);
    120 Static usbd_status usbd_open_pipe_ival
    121 	(struct usbd_interface *, uint8_t, uint8_t, struct usbd_pipe **, int);
    122 static void *usbd_alloc_buffer(struct usbd_xfer *, uint32_t);
    123 static void usbd_free_buffer(struct usbd_xfer *);
    124 static struct usbd_xfer *usbd_alloc_xfer(struct usbd_device *, unsigned int);
    125 static usbd_status usbd_free_xfer(struct usbd_xfer *);
    126 static void usbd_request_async_cb(struct usbd_xfer *, void *, usbd_status);
    127 static void usbd_xfer_timeout(void *);
    128 static void usbd_xfer_timeout_task(void *);
    129 static bool usbd_xfer_probe_timeout(struct usbd_xfer *);
    130 static void usbd_xfer_cancel_timeout_async(struct usbd_xfer *);
    131 
    132 #if defined(USB_DEBUG)
    133 void
    134 usbd_dump_iface(struct usbd_interface *iface)
    135 {
    136 	USBHIST_FUNC();
    137 	USBHIST_CALLARGS(usbdebug, "iface %#jx", (uintptr_t)iface, 0, 0, 0);
    138 
    139 	if (iface == NULL)
    140 		return;
    141 	USBHIST_LOG(usbdebug, "     device = %#jx idesc = %#jx index = %jd",
    142 	    (uintptr_t)iface->ui_dev, (uintptr_t)iface->ui_idesc,
    143 	    iface->ui_index, 0);
    144 	USBHIST_LOG(usbdebug, "     altindex=%jd priv=%#jx",
    145 	    iface->ui_altindex, (uintptr_t)iface->ui_priv, 0, 0);
    146 }
    147 
    148 void
    149 usbd_dump_device(struct usbd_device *dev)
    150 {
    151 	USBHIST_FUNC();
    152 	USBHIST_CALLARGS(usbdebug, "dev = %#jx", (uintptr_t)dev, 0, 0, 0);
    153 
    154 	if (dev == NULL)
    155 		return;
    156 	USBHIST_LOG(usbdebug, "     bus = %#jx default_pipe = %#jx",
    157 	    (uintptr_t)dev->ud_bus, (uintptr_t)dev->ud_pipe0, 0, 0);
    158 	USBHIST_LOG(usbdebug, "     address = %jd config = %jd depth = %jd ",
    159 	    dev->ud_addr, dev->ud_config, dev->ud_depth, 0);
    160 	USBHIST_LOG(usbdebug, "     speed = %jd self_powered = %jd "
    161 	    "power = %jd langid = %jd",
    162 	    dev->ud_speed, dev->ud_selfpowered, dev->ud_power, dev->ud_langid);
    163 }
    164 
    165 void
    166 usbd_dump_endpoint(struct usbd_endpoint *endp)
    167 {
    168 	USBHIST_FUNC();
    169 	USBHIST_CALLARGS(usbdebug, "endp = %#jx", (uintptr_t)endp, 0, 0, 0);
    170 
    171 	if (endp == NULL)
    172 		return;
    173 	USBHIST_LOG(usbdebug, "    edesc = %#jx refcnt = %jd",
    174 	    (uintptr_t)endp->ue_edesc, endp->ue_refcnt, 0, 0);
    175 	if (endp->ue_edesc)
    176 		USBHIST_LOG(usbdebug, "     bEndpointAddress=0x%02jx",
    177 		    endp->ue_edesc->bEndpointAddress, 0, 0, 0);
    178 }
    179 
    180 void
    181 usbd_dump_queue(struct usbd_pipe *pipe)
    182 {
    183 	struct usbd_xfer *xfer;
    184 
    185 	USBHIST_FUNC();
    186 	USBHIST_CALLARGS(usbdebug, "pipe = %#jx", (uintptr_t)pipe, 0, 0, 0);
    187 
    188 	SIMPLEQ_FOREACH(xfer, &pipe->up_queue, ux_next) {
    189 		USBHIST_LOG(usbdebug, "     xfer = %#jx", (uintptr_t)xfer,
    190 		    0, 0, 0);
    191 	}
    192 }
    193 
    194 void
    195 usbd_dump_pipe(struct usbd_pipe *pipe)
    196 {
    197 	USBHIST_FUNC();
    198 	USBHIST_CALLARGS(usbdebug, "pipe = %#jx", (uintptr_t)pipe, 0, 0, 0);
    199 
    200 	if (pipe == NULL)
    201 		return;
    202 	usbd_dump_iface(pipe->up_iface);
    203 	usbd_dump_device(pipe->up_dev);
    204 	usbd_dump_endpoint(pipe->up_endpoint);
    205 	USBHIST_LOG(usbdebug, "(usbd_dump_pipe)", 0, 0, 0, 0);
    206 	USBHIST_LOG(usbdebug, "     running = %jd aborting = %jd",
    207 	    pipe->up_running, pipe->up_aborting, 0, 0);
    208 	USBHIST_LOG(usbdebug, "     intrxfer = %#jx, repeat = %jd, "
    209 	    "interval = %jd", (uintptr_t)pipe->up_intrxfer, pipe->up_repeat,
    210 	    pipe->up_interval, 0);
    211 }
    212 #endif
    213 
    214 usbd_status
    215 usbd_open_pipe(struct usbd_interface *iface, uint8_t address,
    216 	       uint8_t flags, struct usbd_pipe **pipe)
    217 {
    218 	return (usbd_open_pipe_ival(iface, address, flags, pipe,
    219 				    USBD_DEFAULT_INTERVAL));
    220 }
    221 
    222 usbd_status
    223 usbd_open_pipe_ival(struct usbd_interface *iface, uint8_t address,
    224 		    uint8_t flags, struct usbd_pipe **pipe, int ival)
    225 {
    226 	struct usbd_pipe *p;
    227 	struct usbd_endpoint *ep;
    228 	usbd_status err;
    229 	int i;
    230 
    231 	USBHIST_FUNC();
    232 	USBHIST_CALLARGS(usbdebug, "iface = %#jx address = %#jx flags = %#jx",
    233 	    (uintptr_t)iface, address, flags, 0);
    234 
    235 	for (i = 0; i < iface->ui_idesc->bNumEndpoints; i++) {
    236 		ep = &iface->ui_endpoints[i];
    237 		if (ep->ue_edesc == NULL)
    238 			return USBD_IOERROR;
    239 		if (ep->ue_edesc->bEndpointAddress == address)
    240 			goto found;
    241 	}
    242 	return USBD_BAD_ADDRESS;
    243  found:
    244 	err = usbd_setup_pipe_flags(iface->ui_dev, iface, ep, ival, &p, flags);
    245 	if (err)
    246 		return err;
    247 	*pipe = p;
    248 	SDT_PROBE5(usb, device, pipe, open,
    249 	    iface, address, flags, ival, p);
    250 	return USBD_NORMAL_COMPLETION;
    251 }
    252 
    253 usbd_status
    254 usbd_open_pipe_intr(struct usbd_interface *iface, uint8_t address,
    255 		    uint8_t flags, struct usbd_pipe **pipe,
    256 		    void *priv, void *buffer, uint32_t len,
    257 		    usbd_callback cb, int ival)
    258 {
    259 	usbd_status err;
    260 	struct usbd_xfer *xfer;
    261 	struct usbd_pipe *ipipe;
    262 
    263 	USBHIST_FUNC();
    264 	USBHIST_CALLARGS(usbdebug, "address = %#jx flags = %#jx len = %jd",
    265 	    address, flags, len, 0);
    266 
    267 	err = usbd_open_pipe_ival(iface, address,
    268 				  USBD_EXCLUSIVE_USE | (flags & USBD_MPSAFE),
    269 				  &ipipe, ival);
    270 	if (err)
    271 		return err;
    272 	err = usbd_create_xfer(ipipe, len, flags, 0, &xfer);
    273 	if (err)
    274 		goto bad1;
    275 
    276 	usbd_setup_xfer(xfer, priv, buffer, len, flags, USBD_NO_TIMEOUT, cb);
    277 	ipipe->up_intrxfer = xfer;
    278 	ipipe->up_repeat = 1;
    279 	err = usbd_transfer(xfer);
    280 	*pipe = ipipe;
    281 	if (err != USBD_IN_PROGRESS)
    282 		goto bad3;
    283 	SDT_PROBE7(usb, device, pipe, open__intr,
    284 	    iface, address, flags, ival, cb, priv, ipipe);
    285 	return USBD_NORMAL_COMPLETION;
    286 
    287  bad3:
    288 	ipipe->up_intrxfer = NULL;
    289 	ipipe->up_repeat = 0;
    290 
    291 	usbd_destroy_xfer(xfer);
    292  bad1:
    293 	usbd_close_pipe(ipipe);
    294 	return err;
    295 }
    296 
    297 usbd_status
    298 usbd_close_pipe(struct usbd_pipe *pipe)
    299 {
    300 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
    301 
    302 	KASSERT(pipe != NULL);
    303 
    304 	usbd_lock_pipe(pipe);
    305 	SDT_PROBE1(usb, device, pipe, close,  pipe);
    306 
    307 	if (!SIMPLEQ_EMPTY(&pipe->up_queue)) {
    308 		printf("WARNING: pipe closed with active xfers on addr %d\n",
    309 		    pipe->up_dev->ud_addr);
    310 		usbd_ar_pipe(pipe);
    311 	}
    312 
    313 	KASSERT(SIMPLEQ_EMPTY(&pipe->up_queue));
    314 
    315 	pipe->up_methods->upm_close(pipe);
    316 
    317 	usbd_unlock_pipe(pipe);
    318 	if (pipe->up_intrxfer != NULL)
    319 		usbd_destroy_xfer(pipe->up_intrxfer);
    320 	usb_rem_task_wait(pipe->up_dev, &pipe->up_async_task, USB_TASKQ_DRIVER,
    321 	    NULL);
    322 	if (pipe->up_iface) {
    323 		mutex_enter(&pipe->up_iface->ui_pipelock);
    324 		LIST_REMOVE(pipe, up_next);
    325 		mutex_exit(&pipe->up_iface->ui_pipelock);
    326 	}
    327 	usbd_endpoint_release(pipe->up_dev, pipe->up_endpoint);
    328 	kmem_free(pipe, pipe->up_dev->ud_bus->ub_pipesize);
    329 
    330 	return USBD_NORMAL_COMPLETION;
    331 }
    332 
    333 usbd_status
    334 usbd_transfer(struct usbd_xfer *xfer)
    335 {
    336 	struct usbd_pipe *pipe = xfer->ux_pipe;
    337 	usbd_status err;
    338 	unsigned int size, flags;
    339 
    340 	USBHIST_FUNC(); USBHIST_CALLARGS(usbdebug,
    341 	    "xfer = %#jx, flags = %#jx, pipe = %#jx, running = %jd",
    342 	    (uintptr_t)xfer, xfer->ux_flags, (uintptr_t)pipe, pipe->up_running);
    343 	KASSERT(xfer->ux_status == USBD_NOT_STARTED);
    344 	SDT_PROBE1(usb, device, xfer, start,  xfer);
    345 
    346 #ifdef USB_DEBUG
    347 	if (usbdebug > 5)
    348 		usbd_dump_queue(pipe);
    349 #endif
    350 	xfer->ux_done = 0;
    351 
    352 	if (pipe->up_aborting) {
    353 		USBHIST_LOG(usbdebug, "<- done xfer %#jx, aborting",
    354 		    (uintptr_t)xfer, 0, 0, 0);
    355 		SDT_PROBE2(usb, device, xfer, done,  xfer, USBD_CANCELLED);
    356 		return USBD_CANCELLED;
    357 	}
    358 
    359 	KASSERT(xfer->ux_length == 0 || xfer->ux_buf != NULL);
    360 
    361 	size = xfer->ux_length;
    362 	flags = xfer->ux_flags;
    363 
    364 	if (size != 0) {
    365 		/*
    366 		 * Use the xfer buffer if none specified in transfer setup.
    367 		 * isoc transfers always use the xfer buffer, i.e.
    368 		 * ux_buffer is always NULL for isoc.
    369 		 */
    370 		if (xfer->ux_buffer == NULL) {
    371 			xfer->ux_buffer = xfer->ux_buf;
    372 		}
    373 
    374 		/*
    375 		 * If not using the xfer buffer copy data to the
    376 		 * xfer buffer for OUT transfers of >0 length
    377 		 */
    378 		if (xfer->ux_buffer != xfer->ux_buf) {
    379 			KASSERT(xfer->ux_buf);
    380 			if (!usbd_xfer_isread(xfer)) {
    381 				memcpy(xfer->ux_buf, xfer->ux_buffer, size);
    382 			}
    383 		}
    384 	}
    385 
    386 	/* xfer is not valid after the transfer method unless synchronous */
    387 	SDT_PROBE2(usb, device, pipe, transfer__start,  pipe, xfer);
    388 	err = pipe->up_methods->upm_transfer(xfer);
    389 	SDT_PROBE3(usb, device, pipe, transfer__done,  pipe, xfer, err);
    390 
    391 	if (err != USBD_IN_PROGRESS && err) {
    392 		/*
    393 		 * The transfer made it onto the pipe queue, but didn't get
    394 		 * accepted by the HCD for some reason.  It needs removing
    395 		 * from the pipe queue.
    396 		 */
    397 		USBHIST_LOG(usbdebug, "xfer failed: %jd, reinserting",
    398 		    err, 0, 0, 0);
    399 		usbd_lock_pipe(pipe);
    400 		SDT_PROBE1(usb, device, xfer, preabort,  xfer);
    401 #ifdef DIAGNOSTIC
    402 		xfer->ux_state = XFER_BUSY;
    403 #endif
    404 		SIMPLEQ_REMOVE_HEAD(&pipe->up_queue, ux_next);
    405 		if (pipe->up_serialise)
    406 			usbd_start_next(pipe);
    407 		usbd_unlock_pipe(pipe);
    408 	}
    409 
    410 	if (!(flags & USBD_SYNCHRONOUS)) {
    411 		USBHIST_LOG(usbdebug, "<- done xfer %#jx, not sync (err %jd)",
    412 		    (uintptr_t)xfer, err, 0, 0);
    413 		if (err != USBD_IN_PROGRESS) /* XXX Possible?  */
    414 			SDT_PROBE2(usb, device, xfer, done,  xfer, err);
    415 		return err;
    416 	}
    417 
    418 	if (err != USBD_IN_PROGRESS) {
    419 		USBHIST_LOG(usbdebug, "<- done xfer %#jx, sync (err %jd)",
    420 		    (uintptr_t)xfer, err, 0, 0);
    421 		SDT_PROBE2(usb, device, xfer, done,  xfer, err);
    422 		return err;
    423 	}
    424 
    425 	/* Sync transfer, wait for completion. */
    426 	usbd_lock_pipe(pipe);
    427 	while (!xfer->ux_done) {
    428 		if (pipe->up_dev->ud_bus->ub_usepolling)
    429 			panic("usbd_transfer: not done");
    430 		USBHIST_LOG(usbdebug, "<- sleeping on xfer %#jx",
    431 		    (uintptr_t)xfer, 0, 0, 0);
    432 
    433 		err = 0;
    434 		if ((flags & USBD_SYNCHRONOUS_SIG) != 0) {
    435 			err = cv_wait_sig(&xfer->ux_cv, pipe->up_dev->ud_bus->ub_lock);
    436 		} else {
    437 			cv_wait(&xfer->ux_cv, pipe->up_dev->ud_bus->ub_lock);
    438 		}
    439 		if (err) {
    440 			if (!xfer->ux_done) {
    441 				SDT_PROBE1(usb, device, xfer, abort,  xfer);
    442 				pipe->up_methods->upm_abort(xfer);
    443 			}
    444 			break;
    445 		}
    446 	}
    447 	SDT_PROBE2(usb, device, xfer, done,  xfer, xfer->ux_status);
    448 	/* XXX Race to read xfer->ux_status?  */
    449 	usbd_unlock_pipe(pipe);
    450 	return xfer->ux_status;
    451 }
    452 
    453 /* Like usbd_transfer(), but waits for completion. */
    454 usbd_status
    455 usbd_sync_transfer(struct usbd_xfer *xfer)
    456 {
    457 	xfer->ux_flags |= USBD_SYNCHRONOUS;
    458 	return usbd_transfer(xfer);
    459 }
    460 
    461 /* Like usbd_transfer(), but waits for completion and listens for signals. */
    462 usbd_status
    463 usbd_sync_transfer_sig(struct usbd_xfer *xfer)
    464 {
    465 	xfer->ux_flags |= USBD_SYNCHRONOUS | USBD_SYNCHRONOUS_SIG;
    466 	return usbd_transfer(xfer);
    467 }
    468 
    469 static void *
    470 usbd_alloc_buffer(struct usbd_xfer *xfer, uint32_t size)
    471 {
    472 	KASSERT(xfer->ux_buf == NULL);
    473 	KASSERT(size != 0);
    474 
    475 	xfer->ux_bufsize = 0;
    476 #if NUSB_DMA > 0
    477 	struct usbd_bus *bus = xfer->ux_bus;
    478 
    479 	if (bus->ub_usedma) {
    480 		usb_dma_t *dmap = &xfer->ux_dmabuf;
    481 
    482 		KASSERT((bus->ub_dmaflags & USBMALLOC_COHERENT) == 0);
    483 		int err = usb_allocmem(bus, size, 0, bus->ub_dmaflags, dmap);
    484 		if (err) {
    485 			return NULL;
    486 		}
    487 		xfer->ux_buf = KERNADDR(&xfer->ux_dmabuf, 0);
    488 		xfer->ux_bufsize = size;
    489 
    490 		return xfer->ux_buf;
    491 	}
    492 #endif
    493 	KASSERT(xfer->ux_bus->ub_usedma == false);
    494 	xfer->ux_buf = kmem_alloc(size, KM_SLEEP);
    495 	xfer->ux_bufsize = size;
    496 	return xfer->ux_buf;
    497 }
    498 
    499 static void
    500 usbd_free_buffer(struct usbd_xfer *xfer)
    501 {
    502 	KASSERT(xfer->ux_buf != NULL);
    503 	KASSERT(xfer->ux_bufsize != 0);
    504 
    505 	void *buf = xfer->ux_buf;
    506 	uint32_t size = xfer->ux_bufsize;
    507 
    508 	xfer->ux_buf = NULL;
    509 	xfer->ux_bufsize = 0;
    510 
    511 #if NUSB_DMA > 0
    512 	struct usbd_bus *bus = xfer->ux_bus;
    513 
    514 	if (bus->ub_usedma) {
    515 		usb_dma_t *dmap = &xfer->ux_dmabuf;
    516 
    517 		usb_freemem(bus, dmap);
    518 		return;
    519 	}
    520 #endif
    521 	KASSERT(xfer->ux_bus->ub_usedma == false);
    522 
    523 	kmem_free(buf, size);
    524 }
    525 
    526 void *
    527 usbd_get_buffer(struct usbd_xfer *xfer)
    528 {
    529 	return xfer->ux_buf;
    530 }
    531 
    532 struct usbd_pipe *
    533 usbd_get_pipe0(struct usbd_device *dev)
    534 {
    535 
    536 	return dev->ud_pipe0;
    537 }
    538 
    539 static struct usbd_xfer *
    540 usbd_alloc_xfer(struct usbd_device *dev, unsigned int nframes)
    541 {
    542 	struct usbd_xfer *xfer;
    543 
    544 	USBHIST_FUNC();
    545 
    546 	ASSERT_SLEEPABLE();
    547 
    548 	xfer = dev->ud_bus->ub_methods->ubm_allocx(dev->ud_bus, nframes);
    549 	if (xfer == NULL)
    550 		goto out;
    551 	xfer->ux_bus = dev->ud_bus;
    552 	callout_init(&xfer->ux_callout, CALLOUT_MPSAFE);
    553 	callout_setfunc(&xfer->ux_callout, usbd_xfer_timeout, xfer);
    554 	cv_init(&xfer->ux_cv, "usbxfer");
    555 	usb_init_task(&xfer->ux_aborttask, usbd_xfer_timeout_task, xfer,
    556 	    USB_TASKQ_MPSAFE);
    557 
    558 out:
    559 	USBHIST_CALLARGS(usbdebug, "returns %#jx", (uintptr_t)xfer, 0, 0, 0);
    560 
    561 	return xfer;
    562 }
    563 
    564 static usbd_status
    565 usbd_free_xfer(struct usbd_xfer *xfer)
    566 {
    567 	USBHIST_FUNC();
    568 	USBHIST_CALLARGS(usbdebug, "%#jx", (uintptr_t)xfer, 0, 0, 0);
    569 
    570 	if (xfer->ux_buf) {
    571 		usbd_free_buffer(xfer);
    572 	}
    573 
    574 	/* Wait for any straggling timeout to complete. */
    575 	mutex_enter(xfer->ux_bus->ub_lock);
    576 	xfer->ux_timeout_reset = false; /* do not resuscitate */
    577 	callout_halt(&xfer->ux_callout, xfer->ux_bus->ub_lock);
    578 	usb_rem_task_wait(xfer->ux_pipe->up_dev, &xfer->ux_aborttask,
    579 	    USB_TASKQ_HC, xfer->ux_bus->ub_lock);
    580 	mutex_exit(xfer->ux_bus->ub_lock);
    581 
    582 	cv_destroy(&xfer->ux_cv);
    583 	xfer->ux_bus->ub_methods->ubm_freex(xfer->ux_bus, xfer);
    584 	return USBD_NORMAL_COMPLETION;
    585 }
    586 
    587 int
    588 usbd_create_xfer(struct usbd_pipe *pipe, size_t len, unsigned int flags,
    589     unsigned int nframes, struct usbd_xfer **xp)
    590 {
    591 	KASSERT(xp != NULL);
    592 	void *buf = NULL;
    593 
    594 	struct usbd_xfer *xfer = usbd_alloc_xfer(pipe->up_dev, nframes);
    595 	if (xfer == NULL)
    596 		return ENOMEM;
    597 
    598 	xfer->ux_pipe = pipe;
    599 	xfer->ux_flags = flags;
    600 	xfer->ux_nframes = nframes;
    601 	xfer->ux_methods = pipe->up_methods;
    602 
    603 	if (len) {
    604 		buf = usbd_alloc_buffer(xfer, len);
    605 		if (!buf) {
    606 			usbd_free_xfer(xfer);
    607 			return ENOMEM;
    608 		}
    609 	}
    610 
    611 	if (xfer->ux_methods->upm_init) {
    612 		int err = xfer->ux_methods->upm_init(xfer);
    613 		if (err) {
    614 			usbd_free_xfer(xfer);
    615 			return err;
    616 		}
    617 	}
    618 
    619 	*xp = xfer;
    620 	SDT_PROBE5(usb, device, xfer, create,
    621 	    xfer, pipe, len, flags, nframes);
    622 	return 0;
    623 }
    624 
    625 void
    626 usbd_destroy_xfer(struct usbd_xfer *xfer)
    627 {
    628 
    629 	SDT_PROBE1(usb, device, xfer, destroy,  xfer);
    630 	if (xfer->ux_methods->upm_fini)
    631 		xfer->ux_methods->upm_fini(xfer);
    632 
    633 	usbd_free_xfer(xfer);
    634 }
    635 
    636 void
    637 usbd_setup_xfer(struct usbd_xfer *xfer, void *priv, void *buffer,
    638     uint32_t length, uint16_t flags, uint32_t timeout, usbd_callback callback)
    639 {
    640 	KASSERT(xfer->ux_pipe);
    641 
    642 	xfer->ux_priv = priv;
    643 	xfer->ux_buffer = buffer;
    644 	xfer->ux_length = length;
    645 	xfer->ux_actlen = 0;
    646 	xfer->ux_flags = flags;
    647 	xfer->ux_timeout = timeout;
    648 	xfer->ux_status = USBD_NOT_STARTED;
    649 	xfer->ux_callback = callback;
    650 	xfer->ux_rqflags &= ~URQ_REQUEST;
    651 	xfer->ux_nframes = 0;
    652 }
    653 
    654 void
    655 usbd_setup_default_xfer(struct usbd_xfer *xfer, struct usbd_device *dev,
    656     void *priv, uint32_t timeout, usb_device_request_t *req, void *buffer,
    657     uint32_t length, uint16_t flags, usbd_callback callback)
    658 {
    659 	KASSERT(xfer->ux_pipe == dev->ud_pipe0);
    660 
    661 	xfer->ux_priv = priv;
    662 	xfer->ux_buffer = buffer;
    663 	xfer->ux_length = length;
    664 	xfer->ux_actlen = 0;
    665 	xfer->ux_flags = flags;
    666 	xfer->ux_timeout = timeout;
    667 	xfer->ux_status = USBD_NOT_STARTED;
    668 	xfer->ux_callback = callback;
    669 	xfer->ux_request = *req;
    670 	xfer->ux_rqflags |= URQ_REQUEST;
    671 	xfer->ux_nframes = 0;
    672 }
    673 
    674 void
    675 usbd_setup_isoc_xfer(struct usbd_xfer *xfer, void *priv, uint16_t *frlengths,
    676     uint32_t nframes, uint16_t flags, usbd_callback callback)
    677 {
    678 	xfer->ux_priv = priv;
    679 	xfer->ux_buffer = NULL;
    680 	xfer->ux_length = 0;
    681 	xfer->ux_actlen = 0;
    682 	xfer->ux_flags = flags;
    683 	xfer->ux_timeout = USBD_NO_TIMEOUT;
    684 	xfer->ux_status = USBD_NOT_STARTED;
    685 	xfer->ux_callback = callback;
    686 	xfer->ux_rqflags &= ~URQ_REQUEST;
    687 	xfer->ux_frlengths = frlengths;
    688 	xfer->ux_nframes = nframes;
    689 
    690 	for (size_t i = 0; i < xfer->ux_nframes; i++)
    691 		xfer->ux_length += xfer->ux_frlengths[i];
    692 }
    693 
    694 void
    695 usbd_get_xfer_status(struct usbd_xfer *xfer, void **priv,
    696 		     void **buffer, uint32_t *count, usbd_status *status)
    697 {
    698 	if (priv != NULL)
    699 		*priv = xfer->ux_priv;
    700 	if (buffer != NULL)
    701 		*buffer = xfer->ux_buffer;
    702 	if (count != NULL)
    703 		*count = xfer->ux_actlen;
    704 	if (status != NULL)
    705 		*status = xfer->ux_status;
    706 }
    707 
    708 usb_config_descriptor_t *
    709 usbd_get_config_descriptor(struct usbd_device *dev)
    710 {
    711 	KASSERT(dev != NULL);
    712 
    713 	return dev->ud_cdesc;
    714 }
    715 
    716 usb_interface_descriptor_t *
    717 usbd_get_interface_descriptor(struct usbd_interface *iface)
    718 {
    719 	KASSERT(iface != NULL);
    720 
    721 	return iface->ui_idesc;
    722 }
    723 
    724 usb_device_descriptor_t *
    725 usbd_get_device_descriptor(struct usbd_device *dev)
    726 {
    727 	KASSERT(dev != NULL);
    728 
    729 	return &dev->ud_ddesc;
    730 }
    731 
    732 usb_endpoint_descriptor_t *
    733 usbd_interface2endpoint_descriptor(struct usbd_interface *iface, uint8_t index)
    734 {
    735 
    736 	if (index >= iface->ui_idesc->bNumEndpoints)
    737 		return NULL;
    738 	return iface->ui_endpoints[index].ue_edesc;
    739 }
    740 
    741 /* Some drivers may wish to abort requests on the default pipe, *
    742  * but there is no mechanism for getting a handle on it.        */
    743 usbd_status
    744 usbd_abort_default_pipe(struct usbd_device *device)
    745 {
    746 	return usbd_abort_pipe(device->ud_pipe0);
    747 }
    748 
    749 usbd_status
    750 usbd_abort_pipe(struct usbd_pipe *pipe)
    751 {
    752 	usbd_status err;
    753 
    754 	KASSERT(pipe != NULL);
    755 
    756 	usbd_lock_pipe(pipe);
    757 	err = usbd_ar_pipe(pipe);
    758 	usbd_unlock_pipe(pipe);
    759 	return err;
    760 }
    761 
    762 usbd_status
    763 usbd_clear_endpoint_stall(struct usbd_pipe *pipe)
    764 {
    765 	struct usbd_device *dev = pipe->up_dev;
    766 	usbd_status err;
    767 
    768 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
    769 	SDT_PROBE1(usb, device, pipe, clear__endpoint__stall,  pipe);
    770 
    771 	/*
    772 	 * Clearing en endpoint stall resets the endpoint toggle, so
    773 	 * do the same to the HC toggle.
    774 	 */
    775 	SDT_PROBE1(usb, device, pipe, clear__endpoint__toggle,  pipe);
    776 	pipe->up_methods->upm_cleartoggle(pipe);
    777 
    778 	err = usbd_clear_endpoint_feature(dev,
    779 	    pipe->up_endpoint->ue_edesc->bEndpointAddress, UF_ENDPOINT_HALT);
    780 #if 0
    781 XXX should we do this?
    782 	if (!err) {
    783 		pipe->state = USBD_PIPE_ACTIVE;
    784 		/* XXX activate pipe */
    785 	}
    786 #endif
    787 	return err;
    788 }
    789 
    790 void
    791 usbd_clear_endpoint_stall_task(void *arg)
    792 {
    793 	struct usbd_pipe *pipe = arg;
    794 	struct usbd_device *dev = pipe->up_dev;
    795 
    796 	SDT_PROBE1(usb, device, pipe, clear__endpoint__stall,  pipe);
    797 	SDT_PROBE1(usb, device, pipe, clear__endpoint__toggle,  pipe);
    798 	pipe->up_methods->upm_cleartoggle(pipe);
    799 
    800 	(void)usbd_clear_endpoint_feature(dev,
    801 	    pipe->up_endpoint->ue_edesc->bEndpointAddress, UF_ENDPOINT_HALT);
    802 }
    803 
    804 void
    805 usbd_clear_endpoint_stall_async(struct usbd_pipe *pipe)
    806 {
    807 	usb_add_task(pipe->up_dev, &pipe->up_async_task, USB_TASKQ_DRIVER);
    808 }
    809 
    810 void
    811 usbd_clear_endpoint_toggle(struct usbd_pipe *pipe)
    812 {
    813 
    814 	SDT_PROBE1(usb, device, pipe, clear__endpoint__toggle,  pipe);
    815 	pipe->up_methods->upm_cleartoggle(pipe);
    816 }
    817 
    818 usbd_status
    819 usbd_endpoint_count(struct usbd_interface *iface, uint8_t *count)
    820 {
    821 	KASSERT(iface != NULL);
    822 	KASSERT(iface->ui_idesc != NULL);
    823 
    824 	*count = iface->ui_idesc->bNumEndpoints;
    825 	return USBD_NORMAL_COMPLETION;
    826 }
    827 
    828 usbd_status
    829 usbd_interface_count(struct usbd_device *dev, uint8_t *count)
    830 {
    831 
    832 	if (dev->ud_cdesc == NULL)
    833 		return USBD_NOT_CONFIGURED;
    834 	*count = dev->ud_cdesc->bNumInterface;
    835 	return USBD_NORMAL_COMPLETION;
    836 }
    837 
    838 void
    839 usbd_interface2device_handle(struct usbd_interface *iface,
    840 			     struct usbd_device **dev)
    841 {
    842 
    843 	*dev = iface->ui_dev;
    844 }
    845 
    846 usbd_status
    847 usbd_device2interface_handle(struct usbd_device *dev,
    848 			     uint8_t ifaceno, struct usbd_interface **iface)
    849 {
    850 
    851 	if (dev->ud_cdesc == NULL)
    852 		return USBD_NOT_CONFIGURED;
    853 	if (ifaceno >= dev->ud_cdesc->bNumInterface)
    854 		return USBD_INVAL;
    855 	*iface = &dev->ud_ifaces[ifaceno];
    856 	return USBD_NORMAL_COMPLETION;
    857 }
    858 
    859 struct usbd_device *
    860 usbd_pipe2device_handle(struct usbd_pipe *pipe)
    861 {
    862 	KASSERT(pipe != NULL);
    863 
    864 	return pipe->up_dev;
    865 }
    866 
    867 /* XXXX use altno */
    868 usbd_status
    869 usbd_set_interface(struct usbd_interface *iface, int altidx)
    870 {
    871 	usb_device_request_t req;
    872 	usbd_status err;
    873 	void *endpoints;
    874 
    875 	USBHIST_FUNC();
    876 
    877 	mutex_enter(&iface->ui_pipelock);
    878 	if (LIST_FIRST(&iface->ui_pipes) != NULL) {
    879 		err = USBD_IN_USE;
    880 		goto out;
    881 	}
    882 
    883 	endpoints = iface->ui_endpoints;
    884 	int nendpt = iface->ui_idesc->bNumEndpoints;
    885 	USBHIST_CALLARGS(usbdebug, "iface %#jx endpoints = %#jx nendpt %jd",
    886 	    (uintptr_t)iface, (uintptr_t)endpoints,
    887 	    iface->ui_idesc->bNumEndpoints, 0);
    888 	err = usbd_fill_iface_data(iface->ui_dev, iface->ui_index, altidx);
    889 	if (err)
    890 		goto out;
    891 
    892 	/* new setting works, we can free old endpoints */
    893 	if (endpoints != NULL) {
    894 		USBHIST_LOG(usbdebug, "iface %#jx endpoints = %#jx nendpt %jd",
    895 		    (uintptr_t)iface, (uintptr_t)endpoints, nendpt, 0);
    896 		kmem_free(endpoints, nendpt * sizeof(struct usbd_endpoint));
    897 	}
    898 	KASSERT(iface->ui_idesc != NULL);
    899 
    900 	req.bmRequestType = UT_WRITE_INTERFACE;
    901 	req.bRequest = UR_SET_INTERFACE;
    902 	USETW(req.wValue, iface->ui_idesc->bAlternateSetting);
    903 	USETW(req.wIndex, iface->ui_idesc->bInterfaceNumber);
    904 	USETW(req.wLength, 0);
    905 	err = usbd_do_request(iface->ui_dev, &req, 0);
    906 
    907 out:	mutex_exit(&iface->ui_pipelock);
    908 	return err;
    909 }
    910 
    911 int
    912 usbd_get_no_alts(usb_config_descriptor_t *cdesc, int ifaceno)
    913 {
    914 	char *p = (char *)cdesc;
    915 	char *end = p + UGETW(cdesc->wTotalLength);
    916 	usb_interface_descriptor_t *d;
    917 	int n;
    918 
    919 	for (n = 0; p < end; p += d->bLength) {
    920 		d = (usb_interface_descriptor_t *)p;
    921 		if (p + d->bLength <= end &&
    922 		    d->bDescriptorType == UDESC_INTERFACE &&
    923 		    d->bInterfaceNumber == ifaceno)
    924 			n++;
    925 	}
    926 	return n;
    927 }
    928 
    929 int
    930 usbd_get_interface_altindex(struct usbd_interface *iface)
    931 {
    932 	return iface->ui_altindex;
    933 }
    934 
    935 usbd_status
    936 usbd_get_interface(struct usbd_interface *iface, uint8_t *aiface)
    937 {
    938 	usb_device_request_t req;
    939 
    940 	req.bmRequestType = UT_READ_INTERFACE;
    941 	req.bRequest = UR_GET_INTERFACE;
    942 	USETW(req.wValue, 0);
    943 	USETW(req.wIndex, iface->ui_idesc->bInterfaceNumber);
    944 	USETW(req.wLength, 1);
    945 	return usbd_do_request(iface->ui_dev, &req, aiface);
    946 }
    947 
    948 /*** Internal routines ***/
    949 
    950 /* Dequeue all pipe operations, called with bus lock held. */
    951 Static usbd_status
    952 usbd_ar_pipe(struct usbd_pipe *pipe)
    953 {
    954 	struct usbd_xfer *xfer;
    955 
    956 	USBHIST_FUNC();
    957 	USBHIST_CALLARGS(usbdebug, "pipe = %#jx", (uintptr_t)pipe, 0, 0, 0);
    958 	SDT_PROBE1(usb, device, pipe, abort__start,  pipe);
    959 
    960 	KASSERT(mutex_owned(pipe->up_dev->ud_bus->ub_lock));
    961 
    962 #ifdef USB_DEBUG
    963 	if (usbdebug > 5)
    964 		usbd_dump_queue(pipe);
    965 #endif
    966 	pipe->up_repeat = 0;
    967 	pipe->up_running = 0;
    968 	pipe->up_aborting = 1;
    969 	while ((xfer = SIMPLEQ_FIRST(&pipe->up_queue)) != NULL) {
    970 		USBHIST_LOG(usbdebug, "pipe = %#jx xfer = %#jx "
    971 		    "(methods = %#jx)", (uintptr_t)pipe, (uintptr_t)xfer,
    972 		    (uintptr_t)pipe->up_methods, 0);
    973 		if (xfer->ux_status == USBD_NOT_STARTED) {
    974 			SDT_PROBE1(usb, device, xfer, preabort,  xfer);
    975 #ifdef DIAGNOSTIC
    976 			xfer->ux_state = XFER_BUSY;
    977 #endif
    978 			SIMPLEQ_REMOVE_HEAD(&pipe->up_queue, ux_next);
    979 		} else {
    980 			/* Make the HC abort it (and invoke the callback). */
    981 			SDT_PROBE1(usb, device, xfer, abort,  xfer);
    982 			pipe->up_methods->upm_abort(xfer);
    983 			/* XXX only for non-0 usbd_clear_endpoint_stall(pipe); */
    984 		}
    985 	}
    986 	pipe->up_aborting = 0;
    987 	SDT_PROBE1(usb, device, pipe, abort__done,  pipe);
    988 	return USBD_NORMAL_COMPLETION;
    989 }
    990 
    991 /* Called with USB lock held. */
    992 void
    993 usb_transfer_complete(struct usbd_xfer *xfer)
    994 {
    995 	struct usbd_pipe *pipe = xfer->ux_pipe;
    996 	struct usbd_bus *bus = pipe->up_dev->ud_bus;
    997 	int sync = xfer->ux_flags & USBD_SYNCHRONOUS;
    998 	int erred;
    999 	int polling = bus->ub_usepolling;
   1000 	int repeat = pipe->up_repeat;
   1001 
   1002 	USBHIST_FUNC();
   1003 	USBHIST_CALLARGS(usbdebug, "pipe = %#jx xfer = %#jx status = %jd "
   1004 	    "actlen = %jd", (uintptr_t)pipe, (uintptr_t)xfer, xfer->ux_status,
   1005 	    xfer->ux_actlen);
   1006 
   1007 	KASSERT(polling || mutex_owned(pipe->up_dev->ud_bus->ub_lock));
   1008 	KASSERTMSG(xfer->ux_state == XFER_ONQU, "xfer %p state is %x", xfer,
   1009 	    xfer->ux_state);
   1010 	KASSERT(pipe != NULL);
   1011 
   1012 	/*
   1013 	 * If device is known to miss out ack, then pretend that
   1014 	 * output timeout is a success. Userland should handle
   1015 	 * the logic to verify that the operation succeeded.
   1016 	 */
   1017 	if (pipe->up_dev->ud_quirks &&
   1018 	    pipe->up_dev->ud_quirks->uq_flags & UQ_MISS_OUT_ACK &&
   1019 	    xfer->ux_status == USBD_TIMEOUT &&
   1020 	    !usbd_xfer_isread(xfer)) {
   1021 		USBHIST_LOG(usbdebug, "Possible output ack miss for xfer %#jx: "
   1022 		    "hiding write timeout to %jd.%jd for %ju bytes written",
   1023 		    (uintptr_t)xfer, curlwp->l_proc->p_pid, curlwp->l_lid,
   1024 		    xfer->ux_length);
   1025 
   1026 		xfer->ux_status = USBD_NORMAL_COMPLETION;
   1027 		xfer->ux_actlen = xfer->ux_length;
   1028 	}
   1029 
   1030 	erred = xfer->ux_status == USBD_CANCELLED ||
   1031 	        xfer->ux_status == USBD_TIMEOUT;
   1032 
   1033 	if (!repeat) {
   1034 		/* Remove request from queue. */
   1035 
   1036 		KASSERTMSG(!SIMPLEQ_EMPTY(&pipe->up_queue),
   1037 		    "pipe %p is empty, but xfer %p wants to complete", pipe,
   1038 		     xfer);
   1039 		KASSERTMSG(xfer == SIMPLEQ_FIRST(&pipe->up_queue),
   1040 		    "xfer %p is not start of queue (%p is at start)", xfer,
   1041 		   SIMPLEQ_FIRST(&pipe->up_queue));
   1042 
   1043 #ifdef DIAGNOSTIC
   1044 		xfer->ux_state = XFER_BUSY;
   1045 #endif
   1046 		SIMPLEQ_REMOVE_HEAD(&pipe->up_queue, ux_next);
   1047 	}
   1048 	USBHIST_LOG(usbdebug, "xfer %#jx: repeat %jd new head = %#jx",
   1049 	    (uintptr_t)xfer, repeat, (uintptr_t)SIMPLEQ_FIRST(&pipe->up_queue),
   1050 	    0);
   1051 
   1052 	/* Count completed transfers. */
   1053 	++pipe->up_dev->ud_bus->ub_stats.uds_requests
   1054 		[pipe->up_endpoint->ue_edesc->bmAttributes & UE_XFERTYPE];
   1055 
   1056 	xfer->ux_done = 1;
   1057 	if (!xfer->ux_status && xfer->ux_actlen < xfer->ux_length &&
   1058 	    !(xfer->ux_flags & USBD_SHORT_XFER_OK)) {
   1059 		USBHIST_LOG(usbdebug, "short transfer %jd < %jd",
   1060 		    xfer->ux_actlen, xfer->ux_length, 0, 0);
   1061 		xfer->ux_status = USBD_SHORT_XFER;
   1062 	}
   1063 
   1064 	USBHIST_LOG(usbdebug, "xfer %#jx doing done %#jx", (uintptr_t)xfer,
   1065 	    (uintptr_t)pipe->up_methods->upm_done, 0, 0);
   1066 	SDT_PROBE2(usb, device, xfer, done,  xfer, xfer->ux_status);
   1067 	pipe->up_methods->upm_done(xfer);
   1068 
   1069 	if (xfer->ux_length != 0 && xfer->ux_buffer != xfer->ux_buf) {
   1070 		KDASSERTMSG(xfer->ux_actlen <= xfer->ux_length,
   1071 		    "actlen %d length %d",xfer->ux_actlen, xfer->ux_length);
   1072 
   1073 		/* Only if IN transfer */
   1074 		if (usbd_xfer_isread(xfer)) {
   1075 			memcpy(xfer->ux_buffer, xfer->ux_buf, xfer->ux_actlen);
   1076 		}
   1077 	}
   1078 
   1079 	USBHIST_LOG(usbdebug, "xfer %#jx doing callback %#jx status %jd",
   1080 	    (uintptr_t)xfer, (uintptr_t)xfer->ux_callback, xfer->ux_status, 0);
   1081 
   1082 	if (xfer->ux_callback) {
   1083 		if (!polling) {
   1084 			mutex_exit(pipe->up_dev->ud_bus->ub_lock);
   1085 			if (!(pipe->up_flags & USBD_MPSAFE))
   1086 				KERNEL_LOCK(1, curlwp);
   1087 		}
   1088 
   1089 		xfer->ux_callback(xfer, xfer->ux_priv, xfer->ux_status);
   1090 
   1091 		if (!polling) {
   1092 			if (!(pipe->up_flags & USBD_MPSAFE))
   1093 				KERNEL_UNLOCK_ONE(curlwp);
   1094 			mutex_enter(pipe->up_dev->ud_bus->ub_lock);
   1095 		}
   1096 	}
   1097 
   1098 	if (sync && !polling) {
   1099 		USBHIST_LOG(usbdebug, "<- done xfer %#jx, wakeup",
   1100 		    (uintptr_t)xfer, 0, 0, 0);
   1101 		cv_broadcast(&xfer->ux_cv);
   1102 	}
   1103 
   1104 	if (repeat) {
   1105 		xfer->ux_actlen = 0;
   1106 		xfer->ux_status = USBD_NOT_STARTED;
   1107 	} else {
   1108 		/* XXX should we stop the queue on all errors? */
   1109 		if (erred && pipe->up_iface != NULL)	/* not control pipe */
   1110 			pipe->up_running = 0;
   1111 	}
   1112 	if (pipe->up_running && pipe->up_serialise)
   1113 		usbd_start_next(pipe);
   1114 }
   1115 
   1116 /* Called with USB lock held. */
   1117 usbd_status
   1118 usb_insert_transfer(struct usbd_xfer *xfer)
   1119 {
   1120 	struct usbd_pipe *pipe = xfer->ux_pipe;
   1121 	usbd_status err;
   1122 
   1123 	USBHIST_FUNC(); USBHIST_CALLARGS(usbdebug,
   1124 	    "xfer = %#jx pipe = %#jx running = %jd timeout = %jd",
   1125 	    (uintptr_t)xfer, (uintptr_t)pipe,
   1126 	    pipe->up_running, xfer->ux_timeout);
   1127 
   1128 	KASSERT(mutex_owned(pipe->up_dev->ud_bus->ub_lock));
   1129 	KASSERTMSG(xfer->ux_state == XFER_BUSY, "xfer %p state is %x", xfer,
   1130 	    xfer->ux_state);
   1131 
   1132 #ifdef DIAGNOSTIC
   1133 	xfer->ux_state = XFER_ONQU;
   1134 #endif
   1135 	SIMPLEQ_INSERT_TAIL(&pipe->up_queue, xfer, ux_next);
   1136 	if (pipe->up_running && pipe->up_serialise)
   1137 		err = USBD_IN_PROGRESS;
   1138 	else {
   1139 		pipe->up_running = 1;
   1140 		err = USBD_NORMAL_COMPLETION;
   1141 	}
   1142 	USBHIST_LOG(usbdebug, "<- done xfer %#jx, err %jd", (uintptr_t)xfer,
   1143 	    err, 0, 0);
   1144 	return err;
   1145 }
   1146 
   1147 /* Called with USB lock held. */
   1148 void
   1149 usbd_start_next(struct usbd_pipe *pipe)
   1150 {
   1151 	struct usbd_xfer *xfer;
   1152 	usbd_status err;
   1153 
   1154 	USBHIST_FUNC();
   1155 
   1156 	KASSERT(pipe != NULL);
   1157 	KASSERT(pipe->up_methods != NULL);
   1158 	KASSERT(pipe->up_methods->upm_start != NULL);
   1159 	KASSERT(pipe->up_serialise == true);
   1160 
   1161 	int polling = pipe->up_dev->ud_bus->ub_usepolling;
   1162 	KASSERT(polling || mutex_owned(pipe->up_dev->ud_bus->ub_lock));
   1163 
   1164 	/* Get next request in queue. */
   1165 	xfer = SIMPLEQ_FIRST(&pipe->up_queue);
   1166 	USBHIST_CALLARGS(usbdebug, "pipe = %#jx, xfer = %#jx", (uintptr_t)pipe,
   1167 	    (uintptr_t)xfer, 0, 0);
   1168 	if (xfer == NULL) {
   1169 		pipe->up_running = 0;
   1170 	} else {
   1171 		if (!polling)
   1172 			mutex_exit(pipe->up_dev->ud_bus->ub_lock);
   1173 		SDT_PROBE2(usb, device, pipe, start,  pipe, xfer);
   1174 		err = pipe->up_methods->upm_start(xfer);
   1175 		if (!polling)
   1176 			mutex_enter(pipe->up_dev->ud_bus->ub_lock);
   1177 
   1178 		if (err != USBD_IN_PROGRESS) {
   1179 			USBHIST_LOG(usbdebug, "error = %jd", err, 0, 0, 0);
   1180 			pipe->up_running = 0;
   1181 			/* XXX do what? */
   1182 		}
   1183 	}
   1184 
   1185 	KASSERT(polling || mutex_owned(pipe->up_dev->ud_bus->ub_lock));
   1186 }
   1187 
   1188 usbd_status
   1189 usbd_do_request(struct usbd_device *dev, usb_device_request_t *req, void *data)
   1190 {
   1191 
   1192 	return usbd_do_request_flags(dev, req, data, 0, 0,
   1193 	    USBD_DEFAULT_TIMEOUT);
   1194 }
   1195 
   1196 usbd_status
   1197 usbd_do_request_flags(struct usbd_device *dev, usb_device_request_t *req,
   1198     void *data, uint16_t flags, int *actlen, uint32_t timeout)
   1199 {
   1200 	size_t len = UGETW(req->wLength);
   1201 
   1202 	return usbd_do_request_len(dev, req, len, data, flags, actlen, timeout);
   1203 }
   1204 
   1205 usbd_status
   1206 usbd_do_request_len(struct usbd_device *dev, usb_device_request_t *req,
   1207     size_t len, void *data, uint16_t flags, int *actlen, uint32_t timeout)
   1208 {
   1209 	struct usbd_xfer *xfer;
   1210 	usbd_status err;
   1211 
   1212 	KASSERT(len >= UGETW(req->wLength));
   1213 
   1214 	USBHIST_FUNC();
   1215 	USBHIST_CALLARGS(usbdebug, "dev=%#jx req=%jx flags=%jx len=%jx",
   1216 	    (uintptr_t)dev, (uintptr_t)req, flags, len);
   1217 
   1218 	ASSERT_SLEEPABLE();
   1219 
   1220 	int error = usbd_create_xfer(dev->ud_pipe0, len, 0, 0, &xfer);
   1221 	if (error)
   1222 		return error;
   1223 
   1224 	usbd_setup_default_xfer(xfer, dev, 0, timeout, req, data,
   1225 	    UGETW(req->wLength), flags, NULL);
   1226 	KASSERT(xfer->ux_pipe == dev->ud_pipe0);
   1227 	err = usbd_sync_transfer(xfer);
   1228 #if defined(USB_DEBUG) || defined(DIAGNOSTIC)
   1229 	if (xfer->ux_actlen > xfer->ux_length) {
   1230 		USBHIST_LOG(usbdebug, "overrun addr = %jd type = 0x%02jx",
   1231 		    dev->ud_addr, xfer->ux_request.bmRequestType, 0, 0);
   1232 		USBHIST_LOG(usbdebug, "     req = 0x%02jx val = %jd "
   1233 		    "index = %jd",
   1234 		    xfer->ux_request.bRequest, UGETW(xfer->ux_request.wValue),
   1235 		    UGETW(xfer->ux_request.wIndex), 0);
   1236 		USBHIST_LOG(usbdebug, "     rlen = %jd length = %jd "
   1237 		    "actlen = %jd",
   1238 		    UGETW(xfer->ux_request.wLength),
   1239 		    xfer->ux_length, xfer->ux_actlen, 0);
   1240 	}
   1241 #endif
   1242 	if (actlen != NULL)
   1243 		*actlen = xfer->ux_actlen;
   1244 
   1245 	usbd_destroy_xfer(xfer);
   1246 
   1247 	if (err) {
   1248 		USBHIST_LOG(usbdebug, "returning err = %jd", err, 0, 0, 0);
   1249 	}
   1250 	return err;
   1251 }
   1252 
   1253 static void
   1254 usbd_request_async_cb(struct usbd_xfer *xfer, void *priv, usbd_status status)
   1255 {
   1256 	usbd_destroy_xfer(xfer);
   1257 }
   1258 
   1259 /*
   1260  * Execute a request without waiting for completion.
   1261  * Can be used from interrupt context.
   1262  */
   1263 usbd_status
   1264 usbd_request_async(struct usbd_device *dev, struct usbd_xfer *xfer,
   1265     usb_device_request_t *req, void *priv, usbd_callback callback)
   1266 {
   1267 	usbd_status err;
   1268 
   1269 	if (callback == NULL)
   1270 		callback = usbd_request_async_cb;
   1271 
   1272 	usbd_setup_default_xfer(xfer, dev, priv,
   1273 	    USBD_DEFAULT_TIMEOUT, req, NULL, UGETW(req->wLength), 0,
   1274 	    callback);
   1275 	err = usbd_transfer(xfer);
   1276 	if (err != USBD_IN_PROGRESS) {
   1277 		usbd_destroy_xfer(xfer);
   1278 		return (err);
   1279 	}
   1280 	return (USBD_NORMAL_COMPLETION);
   1281 }
   1282 
   1283 const struct usbd_quirks *
   1284 usbd_get_quirks(struct usbd_device *dev)
   1285 {
   1286 #ifdef DIAGNOSTIC
   1287 	if (dev == NULL) {
   1288 		printf("usbd_get_quirks: dev == NULL\n");
   1289 		return 0;
   1290 	}
   1291 #endif
   1292 	return dev->ud_quirks;
   1293 }
   1294 
   1295 /* XXX do periodic free() of free list */
   1296 
   1297 /*
   1298  * Called from keyboard driver when in polling mode.
   1299  */
   1300 void
   1301 usbd_dopoll(struct usbd_interface *iface)
   1302 {
   1303 	iface->ui_dev->ud_bus->ub_methods->ubm_dopoll(iface->ui_dev->ud_bus);
   1304 }
   1305 
   1306 /*
   1307  * This is for keyboard driver as well, which only operates in polling
   1308  * mode from the ask root, etc., prompt and from DDB.
   1309  */
   1310 void
   1311 usbd_set_polling(struct usbd_device *dev, int on)
   1312 {
   1313 	if (on)
   1314 		dev->ud_bus->ub_usepolling++;
   1315 	else
   1316 		dev->ud_bus->ub_usepolling--;
   1317 
   1318 	/* Kick the host controller when switching modes */
   1319 	mutex_enter(dev->ud_bus->ub_lock);
   1320 	dev->ud_bus->ub_methods->ubm_softint(dev->ud_bus);
   1321 	mutex_exit(dev->ud_bus->ub_lock);
   1322 }
   1323 
   1324 
   1325 usb_endpoint_descriptor_t *
   1326 usbd_get_endpoint_descriptor(struct usbd_interface *iface, uint8_t address)
   1327 {
   1328 	struct usbd_endpoint *ep;
   1329 	int i;
   1330 
   1331 	for (i = 0; i < iface->ui_idesc->bNumEndpoints; i++) {
   1332 		ep = &iface->ui_endpoints[i];
   1333 		if (ep->ue_edesc->bEndpointAddress == address)
   1334 			return iface->ui_endpoints[i].ue_edesc;
   1335 	}
   1336 	return NULL;
   1337 }
   1338 
   1339 /*
   1340  * usbd_ratecheck() can limit the number of error messages that occurs.
   1341  * When a device is unplugged it may take up to 0.25s for the hub driver
   1342  * to notice it.  If the driver continuously tries to do I/O operations
   1343  * this can generate a large number of messages.
   1344  */
   1345 int
   1346 usbd_ratecheck(struct timeval *last)
   1347 {
   1348 	static struct timeval errinterval = { 0, 250000 }; /* 0.25 s*/
   1349 
   1350 	return ratecheck(last, &errinterval);
   1351 }
   1352 
   1353 /*
   1354  * Search for a vendor/product pair in an array.  The item size is
   1355  * given as an argument.
   1356  */
   1357 const struct usb_devno *
   1358 usb_match_device(const struct usb_devno *tbl, u_int nentries, u_int sz,
   1359 		 uint16_t vendor, uint16_t product)
   1360 {
   1361 	while (nentries-- > 0) {
   1362 		uint16_t tproduct = tbl->ud_product;
   1363 		if (tbl->ud_vendor == vendor &&
   1364 		    (tproduct == product || tproduct == USB_PRODUCT_ANY))
   1365 			return tbl;
   1366 		tbl = (const struct usb_devno *)((const char *)tbl + sz);
   1367 	}
   1368 	return NULL;
   1369 }
   1370 
   1371 usbd_status
   1372 usbd_get_string(struct usbd_device *dev, int si, char *buf)
   1373 {
   1374 	return usbd_get_string0(dev, si, buf, 1);
   1375 }
   1376 
   1377 usbd_status
   1378 usbd_get_string0(struct usbd_device *dev, int si, char *buf, int unicode)
   1379 {
   1380 	int swap = dev->ud_quirks->uq_flags & UQ_SWAP_UNICODE;
   1381 	usb_string_descriptor_t us;
   1382 	char *s;
   1383 	int i, n;
   1384 	uint16_t c;
   1385 	usbd_status err;
   1386 	int size;
   1387 
   1388 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1389 
   1390 	buf[0] = '\0';
   1391 	if (si == 0)
   1392 		return USBD_INVAL;
   1393 	if (dev->ud_quirks->uq_flags & UQ_NO_STRINGS)
   1394 		return USBD_STALLED;
   1395 	if (dev->ud_langid == USBD_NOLANG) {
   1396 		/* Set up default language */
   1397 		err = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us,
   1398 		    &size);
   1399 		if (err || size < 4) {
   1400 			USBHIST_LOG(usbdebug, "getting lang failed, using 0",
   1401 			    0, 0, 0, 0);
   1402 			dev->ud_langid = 0; /* Well, just pick something then */
   1403 		} else {
   1404 			/* Pick the first language as the default. */
   1405 			dev->ud_langid = UGETW(us.bString[0]);
   1406 		}
   1407 	}
   1408 	err = usbd_get_string_desc(dev, si, dev->ud_langid, &us, &size);
   1409 	if (err)
   1410 		return err;
   1411 	s = buf;
   1412 	n = size / 2 - 1;
   1413 	if (unicode) {
   1414 		for (i = 0; i < n; i++) {
   1415 			c = UGETW(us.bString[i]);
   1416 			if (swap)
   1417 				c = (c >> 8) | (c << 8);
   1418 			s += wput_utf8(s, 3, c);
   1419 		}
   1420 		*s++ = 0;
   1421 	}
   1422 #ifdef COMPAT_30
   1423 	else {
   1424 		for (i = 0; i < n; i++) {
   1425 			c = UGETW(us.bString[i]);
   1426 			if (swap)
   1427 				c = (c >> 8) | (c << 8);
   1428 			*s++ = (c < 0x80) ? c : '?';
   1429 		}
   1430 		*s++ = 0;
   1431 	}
   1432 #endif
   1433 	return USBD_NORMAL_COMPLETION;
   1434 }
   1435 
   1436 /*
   1437  * usbd_xfer_trycomplete(xfer)
   1438  *
   1439  *	Try to claim xfer for completion.  Return true if successful,
   1440  *	false if the xfer has been synchronously aborted or has timed
   1441  *	out.
   1442  *
   1443  *	If this returns true, caller is responsible for setting
   1444  *	xfer->ux_status and calling usb_transfer_complete.  To be used
   1445  *	in a host controller interrupt handler.
   1446  *
   1447  *	Caller must either hold the bus lock or have the bus in polling
   1448  *	mode.
   1449  */
   1450 bool
   1451 usbd_xfer_trycomplete(struct usbd_xfer *xfer)
   1452 {
   1453 	struct usbd_bus *bus __diagused = xfer->ux_bus;
   1454 
   1455 	KASSERT(bus->ub_usepolling || mutex_owned(bus->ub_lock));
   1456 
   1457 	/*
   1458 	 * If software has completed it, either by synchronous abort or
   1459 	 * by timeout, too late.
   1460 	 */
   1461 	if (xfer->ux_status != USBD_IN_PROGRESS)
   1462 		return false;
   1463 
   1464 	/*
   1465 	 * We are completing the xfer.  Cancel the timeout if we can,
   1466 	 * but only asynchronously.  See usbd_xfer_cancel_timeout_async
   1467 	 * for why we need not wait for the callout or task here.
   1468 	 */
   1469 	usbd_xfer_cancel_timeout_async(xfer);
   1470 
   1471 	/* Success!  Note: Caller must set xfer->ux_status afterwar.  */
   1472 	return true;
   1473 }
   1474 
   1475 /*
   1476  * usbd_xfer_abort(xfer)
   1477  *
   1478  *	Try to claim xfer to abort.  If successful, mark it completed
   1479  *	with USBD_CANCELLED and call the bus-specific method to abort
   1480  *	at the hardware level.
   1481  *
   1482  *	To be called in thread context from struct
   1483  *	usbd_pipe_methods::upm_abort.
   1484  *
   1485  *	Caller must hold the bus lock.
   1486  */
   1487 void
   1488 usbd_xfer_abort(struct usbd_xfer *xfer)
   1489 {
   1490 	struct usbd_bus *bus = xfer->ux_bus;
   1491 
   1492 	KASSERT(mutex_owned(bus->ub_lock));
   1493 
   1494 	/*
   1495 	 * If host controller interrupt or timer interrupt has
   1496 	 * completed it, too late.  But the xfer cannot be
   1497 	 * cancelled already -- only one caller can synchronously
   1498 	 * abort.
   1499 	 */
   1500 	KASSERT(xfer->ux_status != USBD_CANCELLED);
   1501 	if (xfer->ux_status != USBD_IN_PROGRESS)
   1502 		return;
   1503 
   1504 	/*
   1505 	 * Cancel the timeout if we can, but only asynchronously; see
   1506 	 * usbd_xfer_cancel_timeout_async for why we need not wait for
   1507 	 * the callout or task here.
   1508 	 */
   1509 	usbd_xfer_cancel_timeout_async(xfer);
   1510 
   1511 	/*
   1512 	 * We beat everyone else.  Claim the status as cancelled and do
   1513 	 * the bus-specific dance to abort the hardware.
   1514 	 */
   1515 	xfer->ux_status = USBD_CANCELLED;
   1516 	bus->ub_methods->ubm_abortx(xfer);
   1517 }
   1518 
   1519 /*
   1520  * usbd_xfer_timeout(xfer)
   1521  *
   1522  *	Called at IPL_SOFTCLOCK when too much time has elapsed waiting
   1523  *	for xfer to complete.  Since we can't abort the xfer at
   1524  *	IPL_SOFTCLOCK, defer to a usb_task to run it in thread context,
   1525  *	unless the xfer has completed or aborted concurrently -- and if
   1526  *	the xfer has also been resubmitted, take care of rescheduling
   1527  *	the callout.
   1528  */
   1529 static void
   1530 usbd_xfer_timeout(void *cookie)
   1531 {
   1532 	struct usbd_xfer *xfer = cookie;
   1533 	struct usbd_bus *bus = xfer->ux_bus;
   1534 	struct usbd_device *dev = xfer->ux_pipe->up_dev;
   1535 
   1536 	/* Acquire the lock so we can transition the timeout state.  */
   1537 	mutex_enter(bus->ub_lock);
   1538 
   1539 	/*
   1540 	 * Use usbd_xfer_probe_timeout to check whether the timeout is
   1541 	 * still valid, or to reschedule the callout if necessary.  If
   1542 	 * it is still valid, schedule the task.
   1543 	 */
   1544 	if (usbd_xfer_probe_timeout(xfer))
   1545 		usb_add_task(dev, &xfer->ux_aborttask, USB_TASKQ_HC);
   1546 
   1547 	/*
   1548 	 * Notify usbd_xfer_cancel_timeout_async that we may have
   1549 	 * scheduled the task.  This causes callout_invoking to return
   1550 	 * false in usbd_xfer_cancel_timeout_async so that it can tell
   1551 	 * which stage in the callout->task->abort process we're at.
   1552 	 */
   1553 	callout_ack(&xfer->ux_callout);
   1554 
   1555 	/* All done -- release the lock.  */
   1556 	mutex_exit(bus->ub_lock);
   1557 }
   1558 
   1559 /*
   1560  * usbd_xfer_timeout_task(xfer)
   1561  *
   1562  *	Called in thread context when too much time has elapsed waiting
   1563  *	for xfer to complete.  Abort the xfer with USBD_TIMEOUT, unless
   1564  *	it has completed or aborted concurrently -- and if the xfer has
   1565  *	also been resubmitted, take care of rescheduling the callout.
   1566  */
   1567 static void
   1568 usbd_xfer_timeout_task(void *cookie)
   1569 {
   1570 	struct usbd_xfer *xfer = cookie;
   1571 	struct usbd_bus *bus = xfer->ux_bus;
   1572 
   1573 	/* Acquire the lock so we can transition the timeout state.  */
   1574 	mutex_enter(bus->ub_lock);
   1575 
   1576 	/*
   1577 	 * Use usbd_xfer_probe_timeout to check whether the timeout is
   1578 	 * still valid, or to reschedule the callout if necessary.  If
   1579 	 * it is not valid -- the timeout has been asynchronously
   1580 	 * cancelled, or the xfer has already been resubmitted -- then
   1581 	 * we're done here.
   1582 	 */
   1583 	if (!usbd_xfer_probe_timeout(xfer))
   1584 		goto out;
   1585 
   1586 	/*
   1587 	 * May have completed or been aborted, but we're the only one
   1588 	 * who can time it out.  If it has completed or been aborted,
   1589 	 * no need to timeout.
   1590 	 */
   1591 	KASSERT(xfer->ux_status != USBD_TIMEOUT);
   1592 	if (xfer->ux_status != USBD_IN_PROGRESS)
   1593 		goto out;
   1594 
   1595 	/*
   1596 	 * We beat everyone else.  Claim the status as timed out and do
   1597 	 * the bus-specific dance to abort the hardware.
   1598 	 */
   1599 	xfer->ux_status = USBD_TIMEOUT;
   1600 	bus->ub_methods->ubm_abortx(xfer);
   1601 
   1602 out:	/* All done -- release the lock.  */
   1603 	mutex_exit(bus->ub_lock);
   1604 }
   1605 
   1606 /*
   1607  * usbd_xfer_probe_timeout(xfer)
   1608  *
   1609  *	Probe the status of xfer's timeout.  Acknowledge and process a
   1610  *	request to reschedule.  Return true if the timeout is still
   1611  *	valid and the caller should take further action (queueing a
   1612  *	task or aborting the xfer), false if it must stop here.
   1613  */
   1614 static bool
   1615 usbd_xfer_probe_timeout(struct usbd_xfer *xfer)
   1616 {
   1617 	struct usbd_bus *bus = xfer->ux_bus;
   1618 	bool valid;
   1619 
   1620 	KASSERT(bus->ub_usepolling || mutex_owned(bus->ub_lock));
   1621 
   1622 	/* The timeout must be set.  */
   1623 	KASSERT(xfer->ux_timeout_set);
   1624 
   1625 	/*
   1626 	 * Neither callout nor task may be pending; they execute
   1627 	 * alternately in lock step.
   1628 	 */
   1629 	KASSERT(!callout_pending(&xfer->ux_callout));
   1630 	KASSERT(!usb_task_pending(xfer->ux_pipe->up_dev, &xfer->ux_aborttask));
   1631 
   1632 	/* There are a few cases... */
   1633 	if (bus->ub_methods->ubm_dying(bus)) {
   1634 		/* Host controller dying.  Drop it all on the floor.  */
   1635 		xfer->ux_timeout_set = false;
   1636 		xfer->ux_timeout_reset = false;
   1637 		valid = false;
   1638 	} else if (xfer->ux_timeout_reset) {
   1639 		/*
   1640 		 * The xfer completed _and_ got resubmitted while we
   1641 		 * waited for the lock.  Acknowledge the request to
   1642 		 * reschedule, and reschedule it if there is a timeout
   1643 		 * and the bus is not polling.
   1644 		 */
   1645 		xfer->ux_timeout_reset = false;
   1646 		if (xfer->ux_timeout && !bus->ub_usepolling) {
   1647 			KASSERT(xfer->ux_timeout_set);
   1648 			callout_schedule(&xfer->ux_callout,
   1649 			    mstohz(xfer->ux_timeout));
   1650 		} else {
   1651 			/* No more callout or task scheduled.  */
   1652 			xfer->ux_timeout_set = false;
   1653 		}
   1654 		valid = false;
   1655 	} else if (xfer->ux_status != USBD_IN_PROGRESS) {
   1656 		/*
   1657 		 * The xfer has completed by hardware completion or by
   1658 		 * software abort, and has not been resubmitted, so the
   1659 		 * timeout must be unset, and is no longer valid for
   1660 		 * the caller.
   1661 		 */
   1662 		xfer->ux_timeout_set = false;
   1663 		valid = false;
   1664 	} else {
   1665 		/*
   1666 		 * The xfer has not yet completed, so the timeout is
   1667 		 * valid.
   1668 		 */
   1669 		valid = true;
   1670 	}
   1671 
   1672 	/* Any reset must have been processed.  */
   1673 	KASSERT(!xfer->ux_timeout_reset);
   1674 
   1675 	/*
   1676 	 * Either we claim the timeout is set, or the callout is idle.
   1677 	 * If the timeout is still set, we may be handing off to the
   1678 	 * task instead, so this is an if but not an iff.
   1679 	 */
   1680 	KASSERT(xfer->ux_timeout_set || !callout_pending(&xfer->ux_callout));
   1681 
   1682 	/*
   1683 	 * The task must be idle now.
   1684 	 *
   1685 	 * - If the caller is the callout, _and_ the timeout is still
   1686 	 *   valid, the caller will schedule it, but it hasn't been
   1687 	 *   scheduled yet.  (If the timeout is not valid, the task
   1688 	 *   should not be scheduled.)
   1689 	 *
   1690 	 * - If the caller is the task, it cannot be scheduled again
   1691 	 *   until the callout runs again, which won't happen until we
   1692 	 *   next release the lock.
   1693 	 */
   1694 	KASSERT(!usb_task_pending(xfer->ux_pipe->up_dev, &xfer->ux_aborttask));
   1695 
   1696 	KASSERT(bus->ub_usepolling || mutex_owned(bus->ub_lock));
   1697 
   1698 	return valid;
   1699 }
   1700 
   1701 /*
   1702  * usbd_xfer_schedule_timeout(xfer)
   1703  *
   1704  *	Ensure that xfer has a timeout.  If the callout is already
   1705  *	queued or the task is already running, request that they
   1706  *	reschedule the callout.  If not, and if we're not polling,
   1707  *	schedule the callout anew.
   1708  *
   1709  *	To be called in thread context from struct
   1710  *	usbd_pipe_methods::upm_start.
   1711  */
   1712 void
   1713 usbd_xfer_schedule_timeout(struct usbd_xfer *xfer)
   1714 {
   1715 	struct usbd_bus *bus = xfer->ux_bus;
   1716 
   1717 	KASSERT(bus->ub_usepolling || mutex_owned(bus->ub_lock));
   1718 
   1719 	if (xfer->ux_timeout_set) {
   1720 		/*
   1721 		 * Callout or task has fired from a prior completed
   1722 		 * xfer but has not yet noticed that the xfer is done.
   1723 		 * Ask it to reschedule itself to ux_timeout.
   1724 		 */
   1725 		xfer->ux_timeout_reset = true;
   1726 	} else if (xfer->ux_timeout && !bus->ub_usepolling) {
   1727 		/* Callout is not scheduled.  Schedule it.  */
   1728 		KASSERT(!callout_pending(&xfer->ux_callout));
   1729 		callout_schedule(&xfer->ux_callout, mstohz(xfer->ux_timeout));
   1730 		xfer->ux_timeout_set = true;
   1731 	}
   1732 
   1733 	KASSERT(bus->ub_usepolling || mutex_owned(bus->ub_lock));
   1734 }
   1735 
   1736 /*
   1737  * usbd_xfer_cancel_timeout_async(xfer)
   1738  *
   1739  *	Cancel the callout and the task of xfer, which have not yet run
   1740  *	to completion, but don't wait for the callout or task to finish
   1741  *	running.
   1742  *
   1743  *	If they have already fired, at worst they are waiting for the
   1744  *	bus lock.  They will see that the xfer is no longer in progress
   1745  *	and give up, or they will see that the xfer has been
   1746  *	resubmitted with a new timeout and reschedule the callout.
   1747  *
   1748  *	If a resubmitted request completed so fast that the callout
   1749  *	didn't have time to process a timer reset, just cancel the
   1750  *	timer reset.
   1751  */
   1752 static void
   1753 usbd_xfer_cancel_timeout_async(struct usbd_xfer *xfer)
   1754 {
   1755 	struct usbd_bus *bus __diagused = xfer->ux_bus;
   1756 
   1757 	KASSERT(bus->ub_usepolling || mutex_owned(bus->ub_lock));
   1758 
   1759 	/*
   1760 	 * If the timer wasn't running anyway, forget about it.  This
   1761 	 * can happen if we are completing an isochronous transfer
   1762 	 * which doesn't use the same timeout logic.
   1763 	 */
   1764 	if (!xfer->ux_timeout_set)
   1765 		return;
   1766 
   1767 	xfer->ux_timeout_reset = false;
   1768 	if (!callout_stop(&xfer->ux_callout)) {
   1769 		/*
   1770 		 * We stopped the callout before it ran.  The timeout
   1771 		 * is no longer set.
   1772 		 */
   1773 		xfer->ux_timeout_set = false;
   1774 	} else if (callout_invoking(&xfer->ux_callout)) {
   1775 		/*
   1776 		 * The callout has begun to run but it has not yet
   1777 		 * acquired the lock and called callout_ack.  The task
   1778 		 * cannot be queued yet, and the callout cannot have
   1779 		 * been rescheduled yet.
   1780 		 *
   1781 		 * By the time the callout acquires the lock, we will
   1782 		 * have transitioned from USBD_IN_PROGRESS to a
   1783 		 * completed status, and possibly also resubmitted the
   1784 		 * xfer and set xfer->ux_timeout_reset = true.  In both
   1785 		 * cases, the callout will DTRT, so no further action
   1786 		 * is needed here.
   1787 		 */
   1788 	} else if (usb_rem_task(xfer->ux_pipe->up_dev, &xfer->ux_aborttask)) {
   1789 		/*
   1790 		 * The callout had fired and scheduled the task, but we
   1791 		 * stopped the task before it could run.  The timeout
   1792 		 * is therefore no longer set -- the next resubmission
   1793 		 * of the xfer must schedule a new timeout.
   1794 		 *
   1795 		 * The callout should not be pending at this point:
   1796 		 * it is scheduled only under the lock, and only when
   1797 		 * xfer->ux_timeout_set is false, or by the callout or
   1798 		 * task itself when xfer->ux_timeout_reset is true.
   1799 		 */
   1800 		xfer->ux_timeout_set = false;
   1801 	}
   1802 
   1803 	/*
   1804 	 * The callout cannot be scheduled and the task cannot be
   1805 	 * queued at this point.  Either we cancelled them, or they are
   1806 	 * already running and waiting for the bus lock.
   1807 	 */
   1808 	KASSERT(!callout_pending(&xfer->ux_callout));
   1809 	KASSERT(!usb_task_pending(xfer->ux_pipe->up_dev, &xfer->ux_aborttask));
   1810 
   1811 	KASSERT(bus->ub_usepolling || mutex_owned(bus->ub_lock));
   1812 }
   1813