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