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