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