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