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