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