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