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