Home | History | Annotate | Line # | Download | only in usb
usbdi.c revision 1.119.12.1
      1 /*	$NetBSD: usbdi.c,v 1.119.12.1 2007/05/22 14:57:49 itohy Exp $	*/
      2 /*	$FreeBSD: src/sys/dev/usb/usbdi.c,v 1.99 2006/11/27 18:39:02 marius Exp $	*/
      3 
      4 /*-
      5  * Copyright (c) 1998 The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Lennart Augustsson (lennart (at) augustsson.net) at
     10  * Carlstedt Research & Technology.
     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  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *        This product includes software developed by the NetBSD
     23  *        Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 #include <sys/cdefs.h>
     42 __KERNEL_RCSID(0, "$NetBSD: usbdi.c,v 1.119.12.1 2007/05/22 14:57:49 itohy Exp $");
     43 /* __FBSDID("$FreeBSD: src/sys/dev/usb/usbdi.c,v 1.99 2006/11/27 18:39:02 marius Exp $"); */
     44 
     45 #ifdef __NetBSD__
     46 #include "opt_compat_netbsd.h"
     47 #endif
     48 
     49 #include <sys/param.h>
     50 #include <sys/systm.h>
     51 #if defined(__NetBSD__) || defined(__OpenBSD__)
     52 #include <sys/kernel.h>
     53 #include <sys/device.h>
     54 #elif defined(__FreeBSD__)
     55 #include <sys/module.h>
     56 #include <sys/bus.h>
     57 #include "usb_if.h"
     58 #if defined(DIAGNOSTIC) && defined(__i386__)
     59 #include <machine/cpu.h>
     60 #endif
     61 #endif
     62 #include <sys/malloc.h>
     63 #include <sys/proc.h>
     64 
     65 #include <machine/bus.h>
     66 
     67 #include <dev/usb/usb.h>
     68 #include <dev/usb/usbdi.h>
     69 #include <dev/usb/usbdi_util.h>
     70 #include <dev/usb/usbdivar.h>
     71 /* #include <dev/usb/usb_mem.h> */
     72 #include <dev/usb/usb_quirks.h>
     73 
     74 #if defined(__FreeBSD__)
     75 #include "usb_if.h"
     76 #define delay(d)	DELAY(d)
     77 #endif
     78 
     79 /* UTF-8 encoding stuff */
     80 #include <fs/unicode.h>
     81 
     82 #ifdef USB_DEBUG
     83 #define DPRINTF(x)	if (usbdebug) logprintf x
     84 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
     85 extern int usbdebug;
     86 #else
     87 #define DPRINTF(x)
     88 #define DPRINTFN(n,x)
     89 #endif
     90 
     91 Static usbd_xfer_handle usbd_alloc_xfer_flag(usbd_device_handle,
     92 	usbd_pipe_handle pipe, enum usbd_waitflg);
     93 Static void usbd_free_buffer_flag(usbd_xfer_handle, enum usbd_waitflg);
     94 Static usbd_status usbd_free_xfer_flag(usbd_xfer_handle, enum usbd_waitflg);
     95 Static usbd_status usbd_ar_pipe(usbd_pipe_handle pipe);
     96 Static void usbd_do_request_async_cb
     97 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
     98 Static void usbd_do_request_async_task(void *);
     99 Static void usbd_start_next(usbd_pipe_handle pipe);
    100 Static usbd_status usbd_open_pipe_ival
    101 	(usbd_interface_handle, u_int8_t, u_int8_t, usbd_pipe_handle *, int);
    102 
    103 int
    104 usbd_xfer_isread(usbd_xfer_handle xfer)
    105 {
    106 	if (xfer->rqflags & URQ_REQUEST)
    107 		return (xfer->request.bmRequestType & UT_READ);
    108 	else
    109 		return (xfer->pipe->endpoint->edesc->bEndpointAddress &
    110 			UE_DIR_IN);
    111 }
    112 
    113 #ifdef USB_DEBUG
    114 void
    115 usbd_dump_iface(struct usbd_interface *iface)
    116 {
    117 	printf("usbd_dump_iface: iface=%p\n", iface);
    118 	if (iface == NULL)
    119 		return;
    120 	printf(" device=%p idesc=%p index=%d altindex=%d priv=%p\n",
    121 	       iface->device, iface->idesc, iface->index, iface->altindex,
    122 	       iface->priv);
    123 }
    124 
    125 void
    126 usbd_dump_device(struct usbd_device *dev)
    127 {
    128 	printf("usbd_dump_device: dev=%p\n", dev);
    129 	if (dev == NULL)
    130 		return;
    131 	printf(" bus=%p default_pipe=%p\n", dev->bus, dev->default_pipe);
    132 	printf(" address=%d config=%d depth=%d speed=%d self_powered=%d "
    133 	       "power=%d langid=%d\n",
    134 	       dev->address, dev->config, dev->depth, dev->speed,
    135 	       dev->self_powered, dev->power, dev->langid);
    136 }
    137 
    138 void
    139 usbd_dump_endpoint(struct usbd_endpoint *endp)
    140 {
    141 	printf("usbd_dump_endpoint: endp=%p\n", endp);
    142 	if (endp == NULL)
    143 		return;
    144 	printf(" edesc=%p refcnt=%d\n", endp->edesc, endp->refcnt);
    145 	if (endp->edesc)
    146 		printf(" bEndpointAddress=0x%02x\n",
    147 		       endp->edesc->bEndpointAddress);
    148 }
    149 
    150 void
    151 usbd_dump_queue(usbd_pipe_handle pipe)
    152 {
    153 	usbd_xfer_handle xfer;
    154 
    155 	printf("usbd_dump_queue: pipe=%p\n", pipe);
    156 	SIMPLEQ_FOREACH(xfer, &pipe->queue, next) {
    157 		printf("  xfer=%p\n", xfer);
    158 	}
    159 }
    160 
    161 void
    162 usbd_dump_pipe(usbd_pipe_handle pipe)
    163 {
    164 	printf("usbd_dump_pipe: pipe=%p\n", pipe);
    165 	if (pipe == NULL)
    166 		return;
    167 	usbd_dump_iface(pipe->iface);
    168 	usbd_dump_device(pipe->device);
    169 	usbd_dump_endpoint(pipe->endpoint);
    170 	printf(" (usbd_dump_pipe:)\n refcnt=%d running=%d aborting=%d\n",
    171 	       pipe->refcnt, pipe->running, pipe->aborting);
    172 	printf(" intrxfer=%p, repeat=%d, interval=%d\n",
    173 	       pipe->intrxfer, pipe->repeat, pipe->interval);
    174 }
    175 #endif
    176 
    177 usbd_status
    178 usbd_open_pipe(usbd_interface_handle iface, u_int8_t address,
    179 	       u_int8_t flags, usbd_pipe_handle *pipe)
    180 {
    181 	return (usbd_open_pipe_ival(iface, address, flags, pipe,
    182 				    USBD_DEFAULT_INTERVAL));
    183 }
    184 
    185 usbd_status
    186 usbd_open_pipe_ival(usbd_interface_handle iface, u_int8_t address,
    187 		    u_int8_t flags, usbd_pipe_handle *pipe, int ival)
    188 {
    189 	usbd_pipe_handle p;
    190 	struct usbd_endpoint *ep;
    191 	usbd_status err;
    192 	int i;
    193 
    194 	DPRINTFN(3,("usbd_open_pipe: iface=%p address=0x%x flags=0x%x\n",
    195 		    iface, address, flags));
    196 
    197 	for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
    198 		ep = &iface->endpoints[i];
    199 		if (ep->edesc == NULL)
    200 			return (USBD_IOERROR);
    201 		if (ep->edesc->bEndpointAddress == address)
    202 			goto found;
    203 	}
    204 	return (USBD_BAD_ADDRESS);
    205  found:
    206 	if ((flags & USBD_EXCLUSIVE_USE) && ep->refcnt != 0)
    207 		return (USBD_IN_USE);
    208 	err = usbd_setup_pipe(iface->device, iface, ep, ival, &p);
    209 	if (err)
    210 		return (err);
    211 	LIST_INSERT_HEAD(&iface->pipes, p, next);
    212 	*pipe = p;
    213 	return (USBD_NORMAL_COMPLETION);
    214 }
    215 
    216 usbd_status
    217 usbd_open_pipe_intr(usbd_interface_handle iface, u_int8_t address,
    218 		    u_int8_t flags, usbd_pipe_handle *pipe,
    219 		    usbd_private_handle priv, void *buffer, u_int32_t len,
    220 		    usbd_callback cb, int ival)
    221 {
    222 	usbd_status err;
    223 	usbd_xfer_handle xfer;
    224 	usbd_pipe_handle ipipe;
    225 
    226 	DPRINTFN(3,("usbd_open_pipe_intr: address=0x%x flags=0x%x len=%d\n",
    227 		    address, flags, len));
    228 
    229 	err = usbd_open_pipe_ival(iface, address, USBD_EXCLUSIVE_USE,
    230 				  &ipipe, ival);
    231 	if (err)
    232 		return (err);
    233 	xfer = usbd_alloc_xfer(iface->device, ipipe);
    234 	if (xfer == NULL) {
    235 		err = USBD_NOMEM;
    236 		goto bad1;
    237 	}
    238 	usbd_setup_xfer(xfer, ipipe, priv, buffer, len, flags,
    239 	    USBD_NO_TIMEOUT, cb);
    240 	ipipe->intrxfer = xfer;
    241 	ipipe->repeat = 1;
    242 	err = usbd_transfer(xfer);
    243 	*pipe = ipipe;
    244 	if (err != USBD_IN_PROGRESS && err)
    245 		goto bad2;
    246 	return (USBD_NORMAL_COMPLETION);
    247 
    248  bad2:
    249 	ipipe->intrxfer = NULL;
    250 	ipipe->repeat = 0;
    251 	usbd_free_xfer(xfer);
    252  bad1:
    253 	usbd_close_pipe(ipipe);
    254 	return (err);
    255 }
    256 
    257 usbd_status
    258 usbd_close_pipe(usbd_pipe_handle pipe)
    259 {
    260 #ifdef DIAGNOSTIC
    261 	if (pipe == NULL) {
    262 		printf("usbd_close_pipe: pipe==NULL\n");
    263 		return (USBD_NORMAL_COMPLETION);
    264 	}
    265 #endif
    266 
    267 	if (--pipe->refcnt != 0)
    268 		return (USBD_NORMAL_COMPLETION);
    269 	if (! SIMPLEQ_EMPTY(&pipe->queue))
    270 		return (USBD_PENDING_REQUESTS);
    271 	LIST_REMOVE(pipe, next);
    272 	pipe->endpoint->refcnt--;
    273 	pipe->methods->close(pipe);
    274 	if (pipe->intrxfer != NULL)
    275 		usbd_free_xfer(pipe->intrxfer);
    276 	free(pipe, M_USB);
    277 	return (USBD_NORMAL_COMPLETION);
    278 }
    279 
    280 usbd_status
    281 usbd_transfer(usbd_xfer_handle xfer)
    282 {
    283 	usbd_pipe_handle pipe = xfer->pipe;
    284 	usbd_status err;
    285 	u_int size;
    286 	int s;
    287 
    288 	DPRINTFN(5,("usbd_transfer: xfer=%p, flags=%d, pipe=%p, running=%d\n",
    289 		    xfer, xfer->flags, pipe, pipe->running));
    290 #ifdef USB_DEBUG
    291 	if (usbdebug > 5)
    292 		usbd_dump_queue(pipe);
    293 #endif
    294 	xfer->done = 0;
    295 
    296 	if (pipe->aborting)
    297 		return (USBD_CANCELLED);
    298 
    299 	size = xfer->length;
    300 	/* If there is no buffer, allocate one. */
    301 	if (!(xfer->rqflags & URQ_MASK_DRV_REQUESTED_BUF) && size != 0) {
    302 		struct usbd_bus *bus = pipe->device->bus;
    303 
    304 #ifdef DIAGNOSTIC
    305 		if (xfer->rqflags & URQ_AUTO_BUF)
    306 			printf("usbd_transfer: has old buffer!\n");
    307 		if (xfer->device->bus->intr_context)
    308 			panic("usbd_transfer: allocm not in process context");
    309 #endif
    310 		err = bus->methods->allocm(bus, xfer,
    311 		    (xfer->flags & USBD_NO_COPY) ? xfer->buffer : NULL,
    312 		    size);
    313 		if (err)
    314 			return (err);
    315 		xfer->rqflags |= URQ_AUTO_BUF;
    316 	}
    317 
    318 	/* Copy data if going out. */
    319 	if (!(xfer->flags & USBD_NO_COPY) && size != 0 &&
    320 	    !usbd_xfer_isread(xfer) && xfer->buffer != xfer->hcbuffer) {
    321 		DPRINTFN(5, ("usbd_transfer: copy %p (alloc) <- %p (buffer), %u bytes\n",
    322 			     xfer->hcbuffer, xfer->buffer, (unsigned)size));
    323 #ifdef DIAGNOSTIC
    324 		if ((xfer->rqflags & (URQ_AUTO_BUF | URQ_DEV_BUF)) == 0)
    325 			panic("usbd_transfer: USBD_NO_COPY required with mapped buffer");
    326 #endif
    327 		memcpy(xfer->hcbuffer, xfer->buffer, size);
    328 	}
    329 
    330 	err = pipe->methods->transfer(xfer);
    331 
    332 	if (err != USBD_IN_PROGRESS && err) {
    333 		/* The transfer has not been queued, so free buffer. */
    334 		if (xfer->rqflags & URQ_AUTO_BUF) {
    335 			struct usbd_bus *bus = pipe->device->bus;
    336 
    337 #ifdef DIAGNOSTIC
    338 			if (bus->intr_context)
    339 				panic("usbd_transfer: freem not in process context");
    340 #endif
    341 			bus->methods->freem(bus, xfer, U_WAITOK);
    342 			xfer->rqflags &= ~URQ_AUTO_BUF;
    343 		}
    344 	}
    345 
    346 	if (!(xfer->flags & USBD_SYNCHRONOUS))
    347 		return (xfer->done ? 0 : USBD_IN_PROGRESS);
    348 
    349 	/* Sync transfer, wait for completion. */
    350 	s = splusb();
    351 	while (!xfer->done) {
    352 		if (pipe->device->bus->use_polling)
    353 			panic("usbd_transfer: not done");
    354 		tsleep(xfer, PRIBIO, "usbsyn", 0);
    355 	}
    356 	splx(s);
    357 	return (xfer->status);
    358 }
    359 
    360 /* Like usbd_transfer(), but waits for completion. */
    361 usbd_status
    362 usbd_sync_transfer(usbd_xfer_handle xfer)
    363 {
    364 	xfer->flags |= USBD_SYNCHRONOUS;
    365 	return (usbd_transfer(xfer));
    366 }
    367 
    368 void *
    369 usbd_alloc_buffer(usbd_xfer_handle xfer, u_int32_t size)
    370 {
    371 	struct usbd_bus *bus = xfer->device->bus;
    372 	usbd_status err;
    373 
    374 	USB_KASSERT2((xfer->rqflags & URQ_MASK_BUF) == 0,
    375 	    ("usbd_alloc_buffer: xfer already has a buffer"));
    376 
    377 #ifdef DIAGNOSTIC
    378 	if (xfer->device->bus->intr_context)
    379 		panic("usbd_alloc_buffer: allocm not in process context");
    380 #endif
    381 	err = bus->methods->allocm(bus, xfer, NULL, size);
    382 	if (err)
    383 		return (NULL);
    384 	xfer->rqflags |= URQ_DEV_BUF;
    385 	return xfer->hcbuffer;
    386 }
    387 
    388 Static void
    389 usbd_free_buffer_flag(usbd_xfer_handle xfer, enum usbd_waitflg waitflg)
    390 {
    391 	struct usbd_bus *bus;
    392 
    393 	USB_KASSERT2((xfer->rqflags & URQ_MASK_BUF) == URQ_DEV_BUF,
    394 	    ("usbd_free_buffer_flag: no/auto buffer"));
    395 
    396 	xfer->rqflags &= ~(URQ_DEV_BUF | URQ_AUTO_BUF);
    397 	bus = xfer->device->bus;
    398 #ifdef DIAGNOSTIC
    399 	if (waitflg == U_WAITOK && bus->intr_context)
    400 		panic("usbd_free_buffer: freem not in process context");
    401 #endif
    402 	bus->methods->freem(bus, xfer, waitflg);
    403 
    404 	xfer->hcbuffer = NULL;
    405 }
    406 
    407 void
    408 usbd_free_buffer(usbd_xfer_handle xfer)
    409 {
    410 	usbd_free_buffer_flag(xfer, U_WAITOK);
    411 }
    412 
    413 void *
    414 usbd_get_buffer(usbd_xfer_handle xfer)
    415 {
    416 	if (!(xfer->rqflags & URQ_DEV_BUF))
    417 		return (NULL);
    418 	return (xfer->hcbuffer);
    419 }
    420 
    421 /*
    422  * map buffer handlings
    423  */
    424 
    425 /* Allocate mapping resources to prepare buffer mapping. */
    426 usbd_status
    427 usbd_map_alloc(usbd_xfer_handle xfer)
    428 {
    429 	struct usbd_bus *bus = xfer->device->bus;
    430 	usbd_status err;
    431 
    432 #ifdef DIAGNOSTIC
    433 	if (bus->intr_context)
    434 		panic("usbd_map_alloc: map_alloc not in process context");
    435 #endif
    436 	USB_KASSERT2((xfer->rqflags & URQ_DEV_MAP_PREPARED) == 0,
    437 	    ("usbd_map_alloc: map already allocated"));
    438 
    439 	err = bus->methods->map_alloc(xfer);
    440 	if (err != USBD_NORMAL_COMPLETION)
    441 		return (err);
    442 
    443 	xfer->rqflags |= URQ_DEV_MAP_PREPARED;
    444 
    445 	return (USBD_NORMAL_COMPLETION);
    446 }
    447 
    448 /* Free mapping resources. */
    449 void
    450 usbd_map_free(usbd_xfer_handle xfer)
    451 {
    452 	struct usbd_bus *bus = xfer->device->bus;
    453 
    454 #ifdef DIAGNOSTIC
    455 	if (bus->intr_context)
    456 		panic("usbd_map_free: map_free not in process context");
    457 #endif
    458 	USB_KASSERT2((xfer->rqflags & URQ_DEV_MAP_PREPARED),
    459 	    ("usbd_map_free: map not allocated"));
    460 
    461 	bus->methods->map_free(xfer);
    462 
    463 	xfer->rqflags &= ~URQ_DEV_MAP_PREPARED;
    464 }
    465 
    466 /* Map plain buffer. */
    467 void
    468 usbd_map_buffer(usbd_xfer_handle xfer, void *buf, u_int32_t size)
    469 {
    470 	struct usbd_bus *bus = xfer->device->bus;
    471 
    472 #ifdef DIAGNOSTIC
    473 	if ((xfer->rqflags & URQ_MASK_BUF))
    474 		panic("usbd_map_buffer: already has buffer (rqflags=%x)",
    475 		    xfer->rqflags);
    476 	if ((xfer->rqflags & URQ_DEV_MAP_PREPARED) == 0 && bus->intr_context)
    477 		panic("usbd_map_buffer: mapm (without map_alloc) not in process context");
    478 #endif
    479 
    480 	bus->methods->mapm(xfer, buf, size);
    481 
    482 	xfer->rqflags |= URQ_DEV_MAP_BUFFER;
    483 }
    484 
    485 /* Map mbuf(9) chain. */
    486 void
    487 usbd_map_buffer_mbuf(usbd_xfer_handle xfer, struct mbuf *chain)
    488 {
    489 	struct usbd_bus *bus = xfer->device->bus;
    490 
    491 #ifdef DIAGNOSTIC
    492 	if ((xfer->rqflags & URQ_MASK_BUF))
    493 		panic("usbd_map_buffer_mbuf: already has buffer (rqflags=%x)",
    494 		    xfer->rqflags);
    495 	if ((xfer->rqflags & URQ_DEV_MAP_PREPARED) == 0 && bus->intr_context)
    496 		panic("usbd_map_buffer_mbuf: mapm_mbuf (without map_alloc) not in process context");
    497 #endif
    498 
    499 	bus->methods->mapm_mbuf(xfer, chain);
    500 
    501 	xfer->rqflags |= URQ_DEV_MAP_MBUF;
    502 }
    503 
    504 /* Unmap plain buffer or mbuf(9) chain. */
    505 void
    506 usbd_unmap_buffer(usbd_xfer_handle xfer)
    507 {
    508 	struct usbd_bus *bus = xfer->device->bus;
    509 
    510 	USB_KASSERT2((xfer->rqflags & (URQ_DEV_MAP_BUFFER | URQ_DEV_MAP_MBUF)),
    511 	    ("usbd_unmap_buffer: no map"));
    512 #ifdef DIAGNOSTIC
    513 	if ((xfer->rqflags & URQ_DEV_MAP_PREPARED) == 0 && bus->intr_context)
    514 		panic("usbd_unmap_buffer: unmapm (without map_alloc) not in process context");
    515 #endif
    516 
    517 	bus->methods->unmapm(xfer);
    518 
    519 	xfer->rqflags &= ~(URQ_DEV_MAP_BUFFER | URQ_DEV_MAP_MBUF);
    520 }
    521 
    522 Static usbd_xfer_handle
    523 usbd_alloc_xfer_flag(usbd_device_handle dev, usbd_pipe_handle pipe,
    524 	enum usbd_waitflg waitflg)
    525 {
    526 	usbd_xfer_handle xfer;
    527 
    528 #ifdef DIAGNOSTIC
    529 	if (waitflg == U_WAITOK && dev->bus->intr_context)
    530 		panic("usbd_alloc_xfer: allocx not in process context");
    531 	if (pipe == NULL)
    532 		panic("usbd_alloc_xfer: pipe == NULL");
    533 #endif
    534 	xfer = dev->bus->methods->allocx(dev->bus, pipe, waitflg);
    535 	if (xfer == NULL)
    536 		return (NULL);
    537 	xfer->pipe = pipe;
    538 	xfer->device = dev;
    539 	usb_callout_init(xfer->timeout_handle);
    540 	DPRINTFN(5,("usbd_alloc_xfer_flag() = %p\n", xfer));
    541 	return (xfer);
    542 }
    543 
    544 usbd_xfer_handle
    545 usbd_alloc_xfer(usbd_device_handle dev, usbd_pipe_handle pipe)
    546 {
    547 	return (usbd_alloc_xfer_flag(dev, pipe, U_WAITOK));
    548 }
    549 
    550 usbd_xfer_handle
    551 usbd_alloc_default_xfer(usbd_device_handle dev)
    552 {
    553 	return (usbd_alloc_xfer_flag(dev, dev->default_pipe, U_WAITOK));
    554 }
    555 
    556 Static usbd_status
    557 usbd_free_xfer_flag(usbd_xfer_handle xfer, enum usbd_waitflg waitflg)
    558 {
    559 	DPRINTFN(5,("usbd_free_xfer_flag: %p %d\n", xfer, waitflg));
    560 	if (xfer->rqflags & (URQ_DEV_BUF | URQ_AUTO_BUF))
    561 		usbd_free_buffer_flag(xfer, waitflg);
    562 	if (xfer->rqflags & (URQ_DEV_MAP_BUFFER | URQ_DEV_MAP_MBUF))
    563 		usbd_unmap_buffer(xfer);
    564 	if (waitflg == U_WAITOK && (xfer->rqflags & URQ_DEV_MAP_PREPARED))
    565 		usbd_map_free(xfer);
    566 #if defined(__NetBSD__) && defined(DIAGNOSTIC)
    567 	if (callout_pending(&xfer->timeout_handle)) {
    568 		callout_stop(&xfer->timeout_handle);
    569 		printf("usbd_free_xfer_flag: timout_handle pending");
    570 	}
    571 #endif
    572 	xfer->device->bus->methods->freex(xfer->device->bus, xfer);
    573 	return (USBD_NORMAL_COMPLETION);
    574 }
    575 
    576 usbd_status
    577 usbd_free_xfer(usbd_xfer_handle xfer)
    578 {
    579 
    580 	return (usbd_free_xfer_flag(xfer, U_WAITOK));
    581 }
    582 
    583 void
    584 usbd_setup_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
    585 		usbd_private_handle priv, void *buffer, u_int32_t length,
    586 		u_int16_t flags, u_int32_t timeout,
    587 		usbd_callback callback)
    588 {
    589 	USB_KASSERT(xfer->pipe == pipe);	/* XXX pipe arg should go */
    590 	xfer->priv = priv;
    591 	xfer->buffer = buffer;
    592 	xfer->length = length;
    593 	xfer->actlen = 0;
    594 	xfer->flags = flags;
    595 	xfer->timeout = timeout;
    596 	xfer->status = USBD_NOT_STARTED;
    597 	xfer->callback = callback;
    598 	xfer->rqflags &= ~URQ_REQUEST;
    599 	xfer->nframes = 0;
    600 }
    601 
    602 void
    603 usbd_setup_default_xfer(usbd_xfer_handle xfer, usbd_device_handle dev,
    604 			usbd_private_handle priv, u_int32_t timeout,
    605 			usb_device_request_t *req, void *buffer,
    606 			u_int32_t length, u_int16_t flags,
    607 			usbd_callback callback)
    608 {
    609 	USB_KASSERT(xfer->pipe == dev->default_pipe);	/* XXX */
    610 	xfer->priv = priv;
    611 	xfer->buffer = buffer;
    612 	xfer->length = length;
    613 	xfer->actlen = 0;
    614 	xfer->flags = flags;
    615 	xfer->timeout = timeout;
    616 	xfer->status = USBD_NOT_STARTED;
    617 	xfer->callback = callback;
    618 	xfer->request = *req;
    619 	xfer->rqflags |= URQ_REQUEST;
    620 	xfer->nframes = 0;
    621 }
    622 
    623 void
    624 usbd_setup_isoc_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
    625 		     usbd_private_handle priv, u_int16_t *frlengths,
    626 		     u_int32_t nframes, u_int16_t flags, usbd_callback callback)
    627 {
    628 	int i;
    629 
    630 	USB_KASSERT(xfer->pipe == pipe);	/* XXX pipe arg should go */
    631 	xfer->priv = priv;
    632 	xfer->buffer = 0;
    633 	xfer->length = 0;
    634 	for (i = 0; i < nframes; i++)
    635 		xfer->length += frlengths[i];
    636 	xfer->actlen = 0;
    637 	xfer->flags = flags;
    638 	xfer->timeout = USBD_NO_TIMEOUT;
    639 	xfer->status = USBD_NOT_STARTED;
    640 	xfer->callback = callback;
    641 	xfer->rqflags &= ~URQ_REQUEST;
    642 	xfer->frlengths = frlengths;
    643 	xfer->nframes = nframes;
    644 }
    645 
    646 void
    647 usbd_get_xfer_status(usbd_xfer_handle xfer, usbd_private_handle *priv,
    648 		     void **buffer, u_int32_t *count, usbd_status *status)
    649 {
    650 	if (priv != NULL)
    651 		*priv = xfer->priv;
    652 	if (buffer != NULL)
    653 		*buffer = xfer->buffer;
    654 	if (count != NULL)
    655 		*count = xfer->actlen;
    656 	if (status != NULL)
    657 		*status = xfer->status;
    658 }
    659 
    660 usb_config_descriptor_t *
    661 usbd_get_config_descriptor(usbd_device_handle dev)
    662 {
    663 #ifdef DIAGNOSTIC
    664 	if (dev == NULL) {
    665 		printf("usbd_get_config_descriptor: dev == NULL\n");
    666 		return (NULL);
    667 	}
    668 #endif
    669 	return (dev->cdesc);
    670 }
    671 
    672 int
    673 usbd_get_speed(usbd_device_handle dev)
    674 {
    675 	return (dev->speed);
    676 }
    677 
    678 usb_interface_descriptor_t *
    679 usbd_get_interface_descriptor(usbd_interface_handle iface)
    680 {
    681 #ifdef DIAGNOSTIC
    682 	if (iface == NULL) {
    683 		printf("usbd_get_interface_descriptor: dev == NULL\n");
    684 		return (NULL);
    685 	}
    686 #endif
    687 	return (iface->idesc);
    688 }
    689 
    690 usb_device_descriptor_t *
    691 usbd_get_device_descriptor(usbd_device_handle dev)
    692 {
    693 	return (&dev->ddesc);
    694 }
    695 
    696 usb_endpoint_descriptor_t *
    697 usbd_interface2endpoint_descriptor(usbd_interface_handle iface, u_int8_t index)
    698 {
    699 	if (index >= iface->idesc->bNumEndpoints)
    700 		return (0);
    701 	return (iface->endpoints[index].edesc);
    702 }
    703 
    704 usbd_status
    705 usbd_abort_pipe(usbd_pipe_handle pipe)
    706 {
    707 	usbd_status err;
    708 	int s;
    709 
    710 #ifdef DIAGNOSTIC
    711 	if (pipe == NULL) {
    712 		printf("usbd_close_pipe: pipe==NULL\n");
    713 		return (USBD_NORMAL_COMPLETION);
    714 	}
    715 #endif
    716 	s = splusb();
    717 	err = usbd_ar_pipe(pipe);
    718 	splx(s);
    719 	return (err);
    720 }
    721 
    722 usbd_status
    723 usbd_abort_default_pipe(usbd_device_handle dev)
    724 {
    725 	return (usbd_abort_pipe(dev->default_pipe));
    726 }
    727 
    728 usbd_status
    729 usbd_clear_endpoint_stall(usbd_pipe_handle pipe)
    730 {
    731 	usbd_device_handle dev = pipe->device;
    732 	usb_device_request_t req;
    733 	usbd_status err;
    734 
    735 	DPRINTFN(8, ("usbd_clear_endpoint_stall\n"));
    736 
    737 	/*
    738 	 * Clearing en endpoint stall resets the endpoint toggle, so
    739 	 * do the same to the HC toggle.
    740 	 */
    741 	pipe->methods->cleartoggle(pipe);
    742 
    743 	req.bmRequestType = UT_WRITE_ENDPOINT;
    744 	req.bRequest = UR_CLEAR_FEATURE;
    745 	USETW(req.wValue, UF_ENDPOINT_HALT);
    746 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
    747 	USETW(req.wLength, 0);
    748 	err = usbd_do_request(dev, &req, 0);
    749 #if 0
    750 XXX should we do this?
    751 	if (!err) {
    752 		pipe->state = USBD_PIPE_ACTIVE;
    753 		/* XXX activate pipe */
    754 	}
    755 #endif
    756 	return (err);
    757 }
    758 
    759 usbd_status
    760 usbd_clear_endpoint_stall_async(usbd_pipe_handle pipe)
    761 {
    762 	usbd_device_handle dev = pipe->device;
    763 	usb_device_request_t req;
    764 	usbd_status err;
    765 
    766 	pipe->methods->cleartoggle(pipe);
    767 
    768 	req.bmRequestType = UT_WRITE_ENDPOINT;
    769 	req.bRequest = UR_CLEAR_FEATURE;
    770 	USETW(req.wValue, UF_ENDPOINT_HALT);
    771 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
    772 	USETW(req.wLength, 0);
    773 	err = usbd_do_request_async(dev, &req, 0);
    774 	return (err);
    775 }
    776 
    777 void
    778 usbd_clear_endpoint_toggle(usbd_pipe_handle pipe)
    779 {
    780 	pipe->methods->cleartoggle(pipe);
    781 }
    782 
    783 usbd_status
    784 usbd_endpoint_count(usbd_interface_handle iface, u_int8_t *count)
    785 {
    786 #ifdef DIAGNOSTIC
    787 	if (iface == NULL || iface->idesc == NULL) {
    788 		printf("usbd_endpoint_count: NULL pointer\n");
    789 		return (USBD_INVAL);
    790 	}
    791 #endif
    792 	*count = iface->idesc->bNumEndpoints;
    793 	return (USBD_NORMAL_COMPLETION);
    794 }
    795 
    796 usbd_status
    797 usbd_interface_count(usbd_device_handle dev, u_int8_t *count)
    798 {
    799 	if (dev->cdesc == NULL)
    800 		return (USBD_NOT_CONFIGURED);
    801 	*count = dev->cdesc->bNumInterface;
    802 	return (USBD_NORMAL_COMPLETION);
    803 }
    804 
    805 void
    806 usbd_interface2device_handle(usbd_interface_handle iface,
    807 			     usbd_device_handle *dev)
    808 {
    809 	*dev = iface->device;
    810 }
    811 
    812 usbd_status
    813 usbd_device2interface_handle(usbd_device_handle dev,
    814 			     u_int8_t ifaceno, usbd_interface_handle *iface)
    815 {
    816 	if (dev->cdesc == NULL)
    817 		return (USBD_NOT_CONFIGURED);
    818 	if (ifaceno >= dev->cdesc->bNumInterface)
    819 		return (USBD_INVAL);
    820 	*iface = &dev->ifaces[ifaceno];
    821 	return (USBD_NORMAL_COMPLETION);
    822 }
    823 
    824 usbd_device_handle
    825 usbd_pipe2device_handle(usbd_pipe_handle pipe)
    826 {
    827 	return (pipe->device);
    828 }
    829 
    830 /* XXXX use altno */
    831 usbd_status
    832 usbd_set_interface(usbd_interface_handle iface, int altidx)
    833 {
    834 	usb_device_request_t req;
    835 	usbd_status err;
    836 	void *endpoints;
    837 
    838 	if (LIST_FIRST(&iface->pipes) != 0)
    839 		return (USBD_IN_USE);
    840 
    841 	endpoints = iface->endpoints;
    842 	err = usbd_fill_iface_data(iface->device, iface->index, altidx);
    843 	if (err)
    844 		return (err);
    845 
    846 	/* new setting works, we can free old endpoints */
    847 	if (endpoints != NULL)
    848 		free(endpoints, M_USB);
    849 
    850 #ifdef DIAGNOSTIC
    851 	if (iface->idesc == NULL) {
    852 		printf("usbd_set_interface: NULL pointer\n");
    853 		return (USBD_INVAL);
    854 	}
    855 #endif
    856 
    857 	req.bmRequestType = UT_WRITE_INTERFACE;
    858 	req.bRequest = UR_SET_INTERFACE;
    859 	USETW(req.wValue, iface->idesc->bAlternateSetting);
    860 	USETW(req.wIndex, iface->idesc->bInterfaceNumber);
    861 	USETW(req.wLength, 0);
    862 	return (usbd_do_request(iface->device, &req, 0));
    863 }
    864 
    865 int
    866 usbd_get_no_alts(usb_config_descriptor_t *cdesc, int ifaceno)
    867 {
    868 	char *p = (char *)cdesc;
    869 	char *end = p + UGETW(cdesc->wTotalLength);
    870 	usb_interface_descriptor_t *d;
    871 	int n;
    872 
    873 	for (n = 0; p < end; p += d->bLength) {
    874 		d = (usb_interface_descriptor_t *)p;
    875 		if (p + d->bLength <= end &&
    876 		    d->bDescriptorType == UDESC_INTERFACE &&
    877 		    d->bInterfaceNumber == ifaceno)
    878 			n++;
    879 	}
    880 	return (n);
    881 }
    882 
    883 int
    884 usbd_get_interface_altindex(usbd_interface_handle iface)
    885 {
    886 	return (iface->altindex);
    887 }
    888 
    889 usbd_status
    890 usbd_get_interface(usbd_interface_handle iface, u_int8_t *aiface)
    891 {
    892 	usb_device_request_t req;
    893 
    894 	req.bmRequestType = UT_READ_INTERFACE;
    895 	req.bRequest = UR_GET_INTERFACE;
    896 	USETW(req.wValue, 0);
    897 	USETW(req.wIndex, iface->idesc->bInterfaceNumber);
    898 	USETW(req.wLength, 1);
    899 	return (usbd_do_request(iface->device, &req, aiface));
    900 }
    901 
    902 /*** Internal routines ***/
    903 
    904 /* Dequeue all pipe operations, called at splusb(). */
    905 Static usbd_status
    906 usbd_ar_pipe(usbd_pipe_handle pipe)
    907 {
    908 	usbd_xfer_handle xfer;
    909 
    910 	SPLUSBCHECK;
    911 
    912 	DPRINTFN(2,("usbd_ar_pipe: pipe=%p\n", pipe));
    913 #ifdef USB_DEBUG
    914 	if (usbdebug > 5)
    915 		usbd_dump_queue(pipe);
    916 #endif
    917 	pipe->repeat = 0;
    918 	pipe->aborting = 1;
    919 	while ((xfer = SIMPLEQ_FIRST(&pipe->queue)) != NULL) {
    920 		DPRINTFN(2,("usbd_ar_pipe: pipe=%p xfer=%p (methods=%p)\n",
    921 			    pipe, xfer, pipe->methods));
    922 		/* Make the HC abort it (and invoke the callback). */
    923 		pipe->methods->abort(xfer);
    924 		USB_KASSERT2(SIMPLEQ_FIRST(&pipe->queue) != xfer,
    925 		    ("usbd_ar_pipe"));
    926 		/* XXX only for non-0 usbd_clear_endpoint_stall(pipe); */
    927 	}
    928 	pipe->aborting = 0;
    929 	return (USBD_NORMAL_COMPLETION);
    930 }
    931 
    932 /* Called at splusb() */
    933 void
    934 usb_transfer_complete(usbd_xfer_handle xfer)
    935 {
    936 	usbd_pipe_handle pipe = xfer->pipe;
    937 	int sync = xfer->flags & USBD_SYNCHRONOUS;
    938 	int erred = xfer->status == USBD_CANCELLED ||
    939 	    xfer->status == USBD_TIMEOUT;
    940 	int repeat, polling;
    941 
    942 	SPLUSBCHECK;
    943 
    944 	DPRINTFN(5, ("usb_transfer_complete: pipe=%p xfer=%p status=%d "
    945 		     "actlen=%d\n", pipe, xfer, xfer->status, xfer->actlen));
    946 #ifdef DIAGNOSTIC
    947 	if (xfer->busy_free != XFER_ONQU) {
    948 		printf("usb_transfer_complete: xfer=%p not busy 0x%08x\n",
    949 		       xfer, xfer->busy_free);
    950 	}
    951 #endif
    952 
    953 #ifdef DIAGNOSTIC
    954 	if (pipe == NULL) {
    955 		printf("usbd_transfer_cb: pipe==0, xfer=%p\n", xfer);
    956 		return;
    957 	}
    958 #endif
    959 	repeat = pipe->repeat;
    960 	polling = pipe->device->bus->use_polling;
    961 	/* XXXX */
    962 	if (polling)
    963 		pipe->running = 0;
    964 
    965 	if (!(xfer->flags & USBD_NO_COPY) && xfer->actlen != 0 &&
    966 	    usbd_xfer_isread(xfer)) {
    967 #ifdef DIAGNOSTIC
    968 		if (xfer->actlen > xfer->length) {
    969 			printf("usb_transfer_complete: actlen > len %d > %d\n",
    970 			       xfer->actlen, xfer->length);
    971 			xfer->actlen = xfer->length;
    972 		}
    973 #endif
    974 		/* Copy data if it is not already in the correct buffer. */
    975 		if (!(xfer->flags & USBD_NO_COPY) && xfer->hcbuffer != NULL) {
    976 			DPRINTFN(5, ("usb_transfer_complete: copy %p (buffer) <- %p (alloc), %u bytes\n",
    977 				     xfer->buffer, xfer->hcbuffer, (unsigned)xfer->actlen));
    978 #ifdef DIAGNOSTIC
    979 			if ((xfer->rqflags & (URQ_AUTO_BUF | URQ_DEV_BUF)) == 0)
    980 				panic("usbd_transfer: USBD_NO_COPY required with mapped buffer");
    981 #endif
    982 			memcpy(xfer->buffer, xfer->hcbuffer, xfer->actlen);
    983 		}
    984 	}
    985 
    986 	/*
    987 	 * if we allocated or mapped the buffer in usbd_transfer()
    988 	 * we unmap it here.
    989 	 */
    990 	if (xfer->rqflags & URQ_AUTO_BUF) {
    991 		if (!repeat) {
    992 			struct usbd_bus *bus = pipe->device->bus;
    993 			bus->methods->freem(bus, xfer, U_NOWAIT);
    994 			xfer->rqflags &= ~URQ_AUTO_BUF;
    995 		}
    996 	}
    997 
    998 	if (!repeat) {
    999 		/* Remove request from queue. */
   1000 #ifdef DIAGNOSTIC
   1001 		xfer->busy_free = XFER_BUSY;
   1002 #endif
   1003 		USB_KASSERT2(SIMPLEQ_FIRST(&pipe->queue) == xfer,
   1004 		    ("usb_transfer_complete: bad dequeue"));
   1005 		SIMPLEQ_REMOVE_HEAD(&pipe->queue, next);
   1006 	}
   1007 	DPRINTFN(5,("usb_transfer_complete: repeat=%d new head=%p\n",
   1008 		    repeat, SIMPLEQ_FIRST(&pipe->queue)));
   1009 
   1010 	/* Count completed transfers. */
   1011 	++pipe->device->bus->stats.uds_requests
   1012 		[pipe->endpoint->edesc->bmAttributes & UE_XFERTYPE];
   1013 
   1014 	xfer->done = 1;
   1015 	if (!xfer->status && xfer->actlen < xfer->length &&
   1016 	    !(xfer->flags & USBD_SHORT_XFER_OK)) {
   1017 		DPRINTFN(-1,("usbd_transfer_cb: short transfer %d<%d\n",
   1018 			     xfer->actlen, xfer->length));
   1019 		xfer->status = USBD_SHORT_XFER;
   1020 	}
   1021 
   1022 	/*
   1023 	 * For repeat operations, call the callback first, as the xfer
   1024 	 * will not go away and the "done" method may modify it. Otherwise
   1025 	 * reverse the order in case the callback wants to free or reuse
   1026 	 * the xfer.
   1027 	 */
   1028 	if (repeat) {
   1029 		if (xfer->callback)
   1030 			xfer->callback(xfer, xfer->priv, xfer->status);
   1031 		pipe->methods->done(xfer);
   1032 	} else {
   1033 		pipe->methods->done(xfer);
   1034 		if (xfer->callback)
   1035 			xfer->callback(xfer, xfer->priv, xfer->status);
   1036 	}
   1037 
   1038 	if (sync && !polling)
   1039 		wakeup(xfer);
   1040 
   1041 	if (!repeat) {
   1042 		/* XXX should we stop the queue on all errors? */
   1043 		if (erred && pipe->iface != NULL)	/* not control pipe */
   1044 			pipe->running = 0;
   1045 		else
   1046 			usbd_start_next(pipe);
   1047 	}
   1048 }
   1049 
   1050 usbd_status
   1051 usb_insert_transfer(usbd_xfer_handle xfer)
   1052 {
   1053 	usbd_pipe_handle pipe = xfer->pipe;
   1054 	usbd_status err;
   1055 	int s;
   1056 
   1057 	DPRINTFN(5,("usb_insert_transfer: pipe=%p running=%d timeout=%d\n",
   1058 		    pipe, pipe->running, xfer->timeout));
   1059 #ifdef DIAGNOSTIC
   1060 	if (xfer->busy_free != XFER_BUSY) {
   1061 		printf("usb_insert_transfer: xfer=%p not busy 0x%08x\n",
   1062 		       xfer, xfer->busy_free);
   1063 		return (USBD_INVAL);
   1064 	}
   1065 	xfer->busy_free = XFER_ONQU;
   1066 #endif
   1067 	s = splusb();
   1068 	USB_KASSERT2(SIMPLEQ_FIRST(&pipe->queue) != xfer,
   1069 	    ("usb_insert_transfer"));
   1070 	SIMPLEQ_INSERT_TAIL(&pipe->queue, xfer, next);
   1071 	if (pipe->running)
   1072 		err = USBD_IN_PROGRESS;
   1073 	else {
   1074 		pipe->running = 1;
   1075 		err = USBD_NORMAL_COMPLETION;
   1076 	}
   1077 	splx(s);
   1078 	return (err);
   1079 }
   1080 
   1081 /* Called at splusb() */
   1082 void
   1083 usbd_start_next(usbd_pipe_handle pipe)
   1084 {
   1085 	usbd_xfer_handle xfer;
   1086 	usbd_status err;
   1087 
   1088 	SPLUSBCHECK;
   1089 
   1090 #ifdef DIAGNOSTIC
   1091 	if (pipe == NULL) {
   1092 		printf("usbd_start_next: pipe == NULL\n");
   1093 		return;
   1094 	}
   1095 	if (pipe->methods == NULL || pipe->methods->start == NULL) {
   1096 		printf("usbd_start_next: pipe=%p no start method\n", pipe);
   1097 		return;
   1098 	}
   1099 #endif
   1100 
   1101 	/* Get next request in queue. */
   1102 	xfer = SIMPLEQ_FIRST(&pipe->queue);
   1103 	DPRINTFN(5, ("usbd_start_next: pipe=%p, xfer=%p\n", pipe, xfer));
   1104 	if (xfer == NULL) {
   1105 		pipe->running = 0;
   1106 	} else {
   1107 		err = pipe->methods->start(xfer);
   1108 		if (err != USBD_IN_PROGRESS) {
   1109 			printf("usbd_start_next: error=%d\n", err);
   1110 			pipe->running = 0;
   1111 			/* XXX do what? */
   1112 		}
   1113 	}
   1114 }
   1115 
   1116 usbd_status
   1117 usbd_do_request(usbd_device_handle dev, usb_device_request_t *req, void *data)
   1118 {
   1119 	return (usbd_do_request_flags(dev, req, data, 0, 0,
   1120 				      USBD_DEFAULT_TIMEOUT));
   1121 }
   1122 
   1123 usbd_status
   1124 usbd_do_request_flags(usbd_device_handle dev, usb_device_request_t *req,
   1125 		      void *data, u_int16_t flags, int *actlen, u_int32_t timo)
   1126 {
   1127 	return (usbd_do_request_flags_pipe(dev, dev->default_pipe, req,
   1128 					   data, flags, actlen, timo));
   1129 }
   1130 
   1131 usbd_status
   1132 usbd_do_request_flags_pipe(usbd_device_handle dev, usbd_pipe_handle pipe,
   1133 	usb_device_request_t *req, void *data, u_int16_t flags, int *actlen,
   1134 	u_int32_t timeout)
   1135 {
   1136 	usbd_xfer_handle xfer;
   1137 	usbd_status err;
   1138 
   1139 #ifdef DIAGNOSTIC
   1140 #if defined(__i386__) && defined(__FreeBSD__)
   1141 	KASSERT(curthread->td_intr_nesting_level == 0,
   1142 	       	("usbd_do_request: in interrupt context"));
   1143 #endif
   1144 	if (dev->bus->intr_context) {
   1145 		panic("usbd_do_request: not in process context");
   1146 	}
   1147 #endif
   1148 
   1149 	xfer = usbd_alloc_xfer(dev, pipe);
   1150 	if (xfer == NULL)
   1151 		return (USBD_NOMEM);
   1152 	xfer->pipe = dev->default_pipe;	/* XXX */
   1153 	/* XXX */
   1154 	usbd_setup_default_xfer(xfer, dev, 0, timeout, req,
   1155 				data, UGETW(req->wLength), flags, 0);
   1156 	/* XXX */
   1157 	xfer->pipe = pipe;
   1158 	err = usbd_sync_transfer(xfer);
   1159 #if defined(USB_DEBUG) || defined(DIAGNOSTIC)
   1160 	if (xfer->actlen > xfer->length) {
   1161 		DPRINTF(("usbd_do_request: overrun addr=%d type=0x%02x req=0x"
   1162 			 "%02x val=%d index=%d rlen=%d length=%d actlen=%d\n",
   1163 			 dev->address, xfer->request.bmRequestType,
   1164 			 xfer->request.bRequest, UGETW(xfer->request.wValue),
   1165 			 UGETW(xfer->request.wIndex),
   1166 			 UGETW(xfer->request.wLength),
   1167 			 xfer->length, xfer->actlen));
   1168 	}
   1169 #endif
   1170 	if (actlen != NULL)
   1171 		*actlen = xfer->actlen;
   1172 	if (err == USBD_STALLED) {
   1173 		/*
   1174 		 * The control endpoint has stalled.  Control endpoints
   1175 		 * should not halt, but some may do so anyway so clear
   1176 		 * any halt condition.
   1177 		 */
   1178 		usb_device_request_t treq;
   1179 		usb_status_t status;
   1180 		u_int16_t s;
   1181 		usbd_status nerr;
   1182 
   1183 		treq.bmRequestType = UT_READ_ENDPOINT;
   1184 		treq.bRequest = UR_GET_STATUS;
   1185 		USETW(treq.wValue, 0);
   1186 		USETW(treq.wIndex, 0);
   1187 		USETW(treq.wLength, sizeof(usb_status_t));
   1188 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
   1189 					   &treq, &status,sizeof(usb_status_t),
   1190 					   0, 0);
   1191 		nerr = usbd_sync_transfer(xfer);
   1192 		if (nerr)
   1193 			goto bad;
   1194 		s = UGETW(status.wStatus);
   1195 		DPRINTF(("usbd_do_request: status = 0x%04x\n", s));
   1196 		if (!(s & UES_HALT))
   1197 			goto bad;
   1198 		treq.bmRequestType = UT_WRITE_ENDPOINT;
   1199 		treq.bRequest = UR_CLEAR_FEATURE;
   1200 		USETW(treq.wValue, UF_ENDPOINT_HALT);
   1201 		USETW(treq.wIndex, 0);
   1202 		USETW(treq.wLength, 0);
   1203 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
   1204 					   &treq, &status, 0, 0, 0);
   1205 		nerr = usbd_sync_transfer(xfer);
   1206 		if (nerr)
   1207 			goto bad;
   1208 	}
   1209 
   1210  bad:
   1211 	usbd_free_xfer(xfer);
   1212 	return (err);
   1213 }
   1214 
   1215 void
   1216 usbd_do_request_async_cb(usbd_xfer_handle xfer,
   1217     usbd_private_handle priv, usbd_status status)
   1218 {
   1219 #if defined(USB_DEBUG) || defined(DIAGNOSTIC)
   1220 	if (xfer->actlen > xfer->length) {
   1221 		DPRINTF(("usbd_do_request: overrun addr=%d type=0x%02x req=0x"
   1222 			 "%02x val=%d index=%d rlen=%d length=%d actlen=%d\n",
   1223 			 xfer->pipe->device->address,
   1224 			 xfer->request.bmRequestType,
   1225 			 xfer->request.bRequest, UGETW(xfer->request.wValue),
   1226 			 UGETW(xfer->request.wIndex),
   1227 			 UGETW(xfer->request.wLength),
   1228 			 xfer->length, xfer->actlen));
   1229 	}
   1230 #endif
   1231 	usbd_free_xfer_flag(xfer, U_NOWAIT);
   1232 }
   1233 
   1234 /*
   1235  * Execute a request without waiting for completion.
   1236  * Can be used from interrupt context.
   1237  */
   1238 usbd_status
   1239 usbd_do_request_async(usbd_device_handle dev, usb_device_request_t *req,
   1240 		      void *data)
   1241 {
   1242 	usbd_xfer_handle xfer;
   1243 
   1244 	xfer = usbd_alloc_xfer_flag(dev, dev->default_pipe, U_NOWAIT);
   1245 	if (xfer == NULL)
   1246 		return (USBD_NOMEM);
   1247 	usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT, req,
   1248 	    data, UGETW(req->wLength), 0, usbd_do_request_async_cb);
   1249 
   1250 	/*
   1251 	 * Request will be processed later as a task (in thread context).
   1252 	 */
   1253 	usb_init_task(&xfer->async_task, usbd_do_request_async_task, xfer);
   1254 	usb_add_task(dev, &xfer->async_task, USB_TASKQ_HC);
   1255 
   1256 	return (USBD_IN_PROGRESS);
   1257 }
   1258 
   1259 Static void
   1260 usbd_do_request_async_task(void *arg)
   1261 {
   1262 	usbd_xfer_handle xfer = arg;
   1263 	usbd_status err;
   1264 
   1265 	/* XXX impossible to notify caller the error */
   1266 	err = usbd_transfer(xfer);
   1267 	if (err != USBD_IN_PROGRESS && err) {
   1268 		usbd_free_xfer(xfer);
   1269 	}
   1270 }
   1271 
   1272 const struct usbd_quirks *
   1273 usbd_get_quirks(usbd_device_handle dev)
   1274 {
   1275 #ifdef DIAGNOSTIC
   1276 	if (dev == NULL) {
   1277 		printf("usbd_get_quirks: dev == NULL\n");
   1278 		return 0;
   1279 	}
   1280 #endif
   1281 	return (dev->quirks);
   1282 }
   1283 
   1284 /* XXX do periodic free() of free list */
   1285 
   1286 /*
   1287  * Called from keyboard driver when in polling mode.
   1288  */
   1289 void
   1290 usbd_dopoll(usbd_interface_handle iface)
   1291 {
   1292 	iface->device->bus->methods->do_poll(iface->device->bus);
   1293 }
   1294 
   1295 void
   1296 usbd_set_polling(usbd_device_handle dev, int on)
   1297 {
   1298 	if (on)
   1299 		dev->bus->use_polling++;
   1300 	else
   1301 		dev->bus->use_polling--;
   1302 	/* When polling we need to make sure there is nothing pending to do. */
   1303 	if (dev->bus->use_polling)
   1304 		dev->bus->methods->soft_intr(dev->bus);
   1305 }
   1306 
   1307 
   1308 usb_endpoint_descriptor_t *
   1309 usbd_get_endpoint_descriptor(usbd_interface_handle iface, u_int8_t address)
   1310 {
   1311 	struct usbd_endpoint *ep;
   1312 	int i;
   1313 
   1314 	for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
   1315 		ep = &iface->endpoints[i];
   1316 		if (ep->edesc->bEndpointAddress == address)
   1317 			return (iface->endpoints[i].edesc);
   1318 	}
   1319 	return (0);
   1320 }
   1321 
   1322 /*
   1323  * usbd_ratecheck() can limit the number of error messages that occurs.
   1324  * When a device is unplugged it may take up to 0.25s for the hub driver
   1325  * to notice it.  If the driver continuosly tries to do I/O operations
   1326  * this can generate a large number of messages.
   1327  */
   1328 int
   1329 usbd_ratecheck(struct timeval *last)
   1330 {
   1331 #if defined(__NetBSD__)
   1332 	static struct timeval errinterval = { 0, 250000 }; /* 0.25 s*/
   1333 
   1334 	return (ratecheck(last, &errinterval));
   1335 #elif defined(__FreeBSD__)
   1336 	if (last->tv_sec == time_second)
   1337 		return (0);
   1338 	last->tv_sec = time_second;
   1339 	return (1);
   1340 #endif
   1341 }
   1342 
   1343 /*
   1344  * Search for a vendor/product pair in an array.  The item size is
   1345  * given as an argument.
   1346  */
   1347 const struct usb_devno *
   1348 usb_match_device(const struct usb_devno *tbl, u_int nentries, u_int sz,
   1349 		 u_int16_t vendor, u_int16_t product)
   1350 {
   1351 	while (nentries-- > 0) {
   1352 		u_int16_t tproduct = tbl->ud_product;
   1353 		if (tbl->ud_vendor == vendor &&
   1354 		    (tproduct == product || tproduct == USB_PRODUCT_ANY))
   1355 			return (tbl);
   1356 		tbl = (const struct usb_devno *)((const char *)tbl + sz);
   1357 	}
   1358 	return (NULL);
   1359 }
   1360 
   1361 
   1362 void
   1363 usb_desc_iter_init(usbd_device_handle dev, usbd_desc_iter_t *iter)
   1364 {
   1365 	const usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
   1366 
   1367         iter->cur = (const uByte *)cd;
   1368         iter->end = (const uByte *)cd + UGETW(cd->wTotalLength);
   1369 }
   1370 
   1371 const usb_descriptor_t *
   1372 usb_desc_iter_next(usbd_desc_iter_t *iter)
   1373 {
   1374 	const usb_descriptor_t *desc;
   1375 
   1376 	if (iter->cur + sizeof(usb_descriptor_t) >= iter->end) {
   1377 		if (iter->cur != iter->end)
   1378 			printf("usb_desc_iter_next: bad descriptor\n");
   1379 		return NULL;
   1380 	}
   1381 	desc = (const usb_descriptor_t *)iter->cur;
   1382 	if (desc->bLength == 0) {
   1383 		printf("usb_desc_iter_next: descriptor length = 0\n");
   1384 		return NULL;
   1385 	}
   1386 	iter->cur += desc->bLength;
   1387 	if (iter->cur > iter->end) {
   1388 		printf("usb_desc_iter_next: descriptor length too large\n");
   1389 		return NULL;
   1390 	}
   1391 	return desc;
   1392 }
   1393 
   1394 usbd_status
   1395 usbd_get_string(usbd_device_handle dev, int si, char *buf)
   1396 {
   1397 	return usbd_get_string0(dev, si, buf, 1);
   1398 }
   1399 
   1400 usbd_status
   1401 usbd_get_string0(usbd_device_handle dev, int si, char *buf, int unicode)
   1402 {
   1403 	int swap = dev->quirks->uq_flags & UQ_SWAP_UNICODE;
   1404 	usb_string_descriptor_t us;
   1405 	char *s;
   1406 	int i, n;
   1407 	u_int16_t c;
   1408 	usbd_status err;
   1409 	int size;
   1410 
   1411 	buf[0] = '\0';
   1412 	if (si == 0)
   1413 		return (USBD_INVAL);
   1414 	if (dev->quirks->uq_flags & UQ_NO_STRINGS)
   1415 		return (USBD_STALLED);
   1416 	if (dev->langid == USBD_NOLANG) {
   1417 		/* Set up default language */
   1418 		err = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us,
   1419 		    &size);
   1420 		if (err || size < 4) {
   1421 			DPRINTFN(-1,("usbd_get_string: getting lang failed, using 0\n"));
   1422 			dev->langid = 0; /* Well, just pick something then */
   1423 		} else {
   1424 			/* Pick the first language as the default. */
   1425 			dev->langid = UGETW(us.bString[0]);
   1426 		}
   1427 	}
   1428 	err = usbd_get_string_desc(dev, si, dev->langid, &us, &size);
   1429 	if (err)
   1430 		return (err);
   1431 	s = buf;
   1432 	n = size / 2 - 1;
   1433 	if (unicode) {
   1434 		for (i = 0; i < n; i++) {
   1435 			c = UGETW(us.bString[i]);
   1436 			if (swap)
   1437 				c = (c >> 8) | (c << 8);
   1438 			s += wput_utf8(s, 3, c);
   1439 		}
   1440 		*s++ = 0;
   1441 	}
   1442 #if defined(__NetBSD__) && defined(COMPAT_30)
   1443 	else {
   1444 		for (i = 0; i < n; i++) {
   1445 			c = UGETW(us.bString[i]);
   1446 			if (swap)
   1447 				c = (c >> 8) | (c << 8);
   1448 			*s++ = (c < 0x80) ? c : '?';
   1449 		}
   1450 		*s++ = 0;
   1451 	}
   1452 #endif
   1453 	return (USBD_NORMAL_COMPLETION);
   1454 }
   1455 
   1456 #if defined(__FreeBSD__)
   1457 int
   1458 usbd_driver_load(module_t mod, int what, void *arg)
   1459 {
   1460 	/* XXX should implement something like a function that removes all generic devices */
   1461 
   1462  	return (0);
   1463 }
   1464 
   1465 #endif
   1466