xref: /netbsd-src/sys/dev/usb/usbdi.c (revision 3b01aba77a7a698587faaae455bbfe740923c1f5)
1 /*	$NetBSD: usbdi.c,v 1.81 2001/04/17 00:05:33 augustss Exp $	*/
2 /*	$FreeBSD: src/sys/dev/usb/usbdi.c,v 1.28 1999/11/17 22:33:49 n_hibma 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@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/param.h>
42 #include <sys/systm.h>
43 #if defined(__NetBSD__) || defined(__OpenBSD__)
44 #include <sys/kernel.h>
45 #include <sys/device.h>
46 #elif defined(__FreeBSD__)
47 #include <sys/module.h>
48 #include <sys/bus.h>
49 #include <sys/conf.h>
50 #include "usb_if.h"
51 #if defined(DIAGNOSTIC) && defined(__i386__)
52 #include <machine/cpu.h>
53 #endif
54 #endif
55 #include <sys/malloc.h>
56 #include <sys/proc.h>
57 
58 #include <machine/bus.h>
59 
60 #include <dev/usb/usb.h>
61 #include <dev/usb/usbdi.h>
62 #include <dev/usb/usbdi_util.h>
63 #include <dev/usb/usbdivar.h>
64 #include <dev/usb/usb_mem.h>
65 
66 #if defined(__FreeBSD__)
67 #include "usb_if.h"
68 #endif
69 
70 #ifdef USB_DEBUG
71 #define DPRINTF(x)	if (usbdebug) logprintf x
72 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
73 extern int usbdebug;
74 #else
75 #define DPRINTF(x)
76 #define DPRINTFN(n,x)
77 #endif
78 
79 Static usbd_status usbd_ar_pipe(usbd_pipe_handle pipe);
80 Static void usbd_do_request_async_cb
81 (usbd_xfer_handle, usbd_private_handle, usbd_status);
82 Static void usbd_start_next(usbd_pipe_handle pipe);
83 Static usbd_status usbd_open_pipe_ival
84 (usbd_interface_handle, u_int8_t, u_int8_t, usbd_pipe_handle *, int);
85 
86 Static int usbd_nbuses = 0;
87 
88 void
89 usbd_init(void)
90 {
91 	usbd_nbuses++;
92 }
93 
94 void
95 usbd_finish(void)
96 {
97 	--usbd_nbuses;
98 }
99 
100 static __inline int
101 usbd_xfer_isread(usbd_xfer_handle xfer)
102 {
103 	if (xfer->rqflags & URQ_REQUEST)
104 		return (xfer->request.bmRequestType & UT_READ);
105 	else
106 		return (xfer->pipe->endpoint->edesc->bEndpointAddress &
107 			UE_DIR_IN);
108 }
109 
110 #ifdef USB_DEBUG
111 void usbd_dump_queue(usbd_pipe_handle pipe);
112 void
113 usbd_dump_queue(usbd_pipe_handle pipe)
114 {
115 	usbd_xfer_handle xfer;
116 
117 	printf("usbd_dump_queue: pipe=%p\n", pipe);
118 	for (xfer = SIMPLEQ_FIRST(&pipe->queue);
119 	     xfer;
120 	     xfer = SIMPLEQ_NEXT(xfer, next)) {
121 		printf("  xfer=%p\n", xfer);
122 	}
123 }
124 #endif
125 
126 usbd_status
127 usbd_open_pipe(usbd_interface_handle iface, u_int8_t address,
128 	       u_int8_t flags, usbd_pipe_handle *pipe)
129 {
130 	return (usbd_open_pipe_ival(iface, address, flags, pipe,
131 				    USBD_DEFAULT_INTERVAL));
132 }
133 
134 usbd_status
135 usbd_open_pipe_ival(usbd_interface_handle iface, u_int8_t address,
136 		    u_int8_t flags, usbd_pipe_handle *pipe, int ival)
137 {
138 	usbd_pipe_handle p;
139 	struct usbd_endpoint *ep;
140 	usbd_status err;
141 	int i;
142 
143 	DPRINTFN(3,("usbd_open_pipe: iface=%p address=0x%x flags=0x%x\n",
144 		    iface, address, flags));
145 
146 	for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
147 		ep = &iface->endpoints[i];
148 		if (ep->edesc == NULL)
149 			return (USBD_IOERROR);
150 		if (ep->edesc->bEndpointAddress == address)
151 			goto found;
152 	}
153 	return (USBD_BAD_ADDRESS);
154  found:
155 	if ((flags & USBD_EXCLUSIVE_USE) && ep->refcnt != 0)
156 		return (USBD_IN_USE);
157 	err = usbd_setup_pipe(iface->device, iface, ep, ival, &p);
158 	if (err)
159 		return (err);
160 	LIST_INSERT_HEAD(&iface->pipes, p, next);
161 	*pipe = p;
162 	return (USBD_NORMAL_COMPLETION);
163 }
164 
165 usbd_status
166 usbd_open_pipe_intr(usbd_interface_handle iface, u_int8_t address,
167 		    u_int8_t flags, usbd_pipe_handle *pipe,
168 		    usbd_private_handle priv, void *buffer, u_int32_t len,
169 		    usbd_callback cb, int ival)
170 {
171 	usbd_status err;
172 	usbd_xfer_handle xfer;
173 	usbd_pipe_handle ipipe;
174 
175 	DPRINTFN(3,("usbd_open_pipe_intr: address=0x%x flags=0x%x len=%d\n",
176 		    address, flags, len));
177 
178 	err = usbd_open_pipe_ival(iface, address, USBD_EXCLUSIVE_USE,
179 				  &ipipe, ival);
180 	if (err)
181 		return (err);
182 	xfer = usbd_alloc_xfer(iface->device);
183 	if (xfer == NULL) {
184 		err = USBD_NOMEM;
185 		goto bad1;
186 	}
187 	usbd_setup_xfer(xfer, ipipe, priv, buffer, len, flags,
188 	    USBD_NO_TIMEOUT, cb);
189 	ipipe->intrxfer = xfer;
190 	ipipe->repeat = 1;
191 	err = usbd_transfer(xfer);
192 	*pipe = ipipe;
193 	if (err != USBD_IN_PROGRESS)
194 		goto bad2;
195 	return (USBD_NORMAL_COMPLETION);
196 
197  bad2:
198 	ipipe->intrxfer = NULL;
199 	ipipe->repeat = 0;
200 	usbd_free_xfer(xfer);
201  bad1:
202 	usbd_close_pipe(ipipe);
203 	return (err);
204 }
205 
206 usbd_status
207 usbd_close_pipe(usbd_pipe_handle pipe)
208 {
209 #ifdef DIAGNOSTIC
210 	if (pipe == NULL) {
211 		printf("usbd_close_pipe: pipe==NULL\n");
212 		return (USBD_NORMAL_COMPLETION);
213 	}
214 #endif
215 
216 	if (--pipe->refcnt != 0)
217 		return (USBD_NORMAL_COMPLETION);
218 	if (SIMPLEQ_FIRST(&pipe->queue) != 0)
219 		return (USBD_PENDING_REQUESTS);
220 	LIST_REMOVE(pipe, next);
221 	pipe->endpoint->refcnt--;
222 	pipe->methods->close(pipe);
223 #if defined(__NetBSD__) && defined(DIAGNOSTIC)
224 	if (callout_pending(&pipe->abort_handle)) {
225 		callout_stop(&pipe->abort_handle);
226 		printf("usbd_close_pipe: abort_handle pending");
227 	}
228 #endif
229 	if (pipe->intrxfer != NULL)
230 		usbd_free_xfer(pipe->intrxfer);
231 	free(pipe, M_USB);
232 	return (USBD_NORMAL_COMPLETION);
233 }
234 
235 usbd_status
236 usbd_transfer(usbd_xfer_handle xfer)
237 {
238 	usbd_pipe_handle pipe = xfer->pipe;
239 	usb_dma_t *dmap = &xfer->dmabuf;
240 	usbd_status err;
241 	u_int size;
242 	int s;
243 
244 	DPRINTFN(5,("usbd_transfer: xfer=%p, flags=%d, pipe=%p, running=%d\n",
245 		    xfer, xfer->flags, pipe, pipe->running));
246 #ifdef USB_DEBUG
247 	if (usbdebug > 5)
248 		usbd_dump_queue(pipe);
249 #endif
250 	xfer->done = 0;
251 
252 	if (pipe->aborting)
253 		return (USBD_CANCELLED);
254 
255 	size = xfer->length;
256 	/* If there is no buffer, allocate one. */
257 	if (!(xfer->rqflags & URQ_DEV_DMABUF) && size != 0) {
258 		struct usbd_bus *bus = pipe->device->bus;
259 
260 #ifdef DIAGNOSTIC
261 		if (xfer->rqflags & URQ_AUTO_DMABUF)
262 			printf("usbd_transfer: has old buffer!\n");
263 #endif
264 		err = bus->methods->allocm(bus, dmap, size);
265 		if (err)
266 			return (err);
267 		xfer->rqflags |= URQ_AUTO_DMABUF;
268 	}
269 
270 	/* Copy data if going out. */
271 	if (!(xfer->flags & USBD_NO_COPY) && size != 0 &&
272 	    !usbd_xfer_isread(xfer))
273 		memcpy(KERNADDR(dmap), xfer->buffer, size);
274 
275 	err = pipe->methods->transfer(xfer);
276 
277 	if (err != USBD_IN_PROGRESS && err) {
278 		/* The transfer has not been queued, so free buffer. */
279 		if (xfer->rqflags & URQ_AUTO_DMABUF) {
280 			struct usbd_bus *bus = pipe->device->bus;
281 
282 			bus->methods->freem(bus, &xfer->dmabuf);
283 			xfer->rqflags &= ~URQ_AUTO_DMABUF;
284 		}
285 	}
286 
287 	if (!(xfer->flags & USBD_SYNCHRONOUS))
288 		return (err);
289 
290 	/* Sync transfer, wait for completion. */
291 	if (err != USBD_IN_PROGRESS)
292 		return (err);
293 	s = splusb();
294 	if (!xfer->done) {
295 		if (pipe->device->bus->use_polling)
296 			panic("usbd_transfer: not done\n");
297 		tsleep(xfer, PRIBIO, "usbsyn", 0);
298 	}
299 	splx(s);
300 	return (xfer->status);
301 }
302 
303 /* Like usbd_transfer(), but waits for completion. */
304 usbd_status
305 usbd_sync_transfer(usbd_xfer_handle xfer)
306 {
307 	xfer->flags |= USBD_SYNCHRONOUS;
308 	return (usbd_transfer(xfer));
309 }
310 
311 void *
312 usbd_alloc_buffer(usbd_xfer_handle xfer, u_int32_t size)
313 {
314 	struct usbd_bus *bus = xfer->device->bus;
315 	usbd_status err;
316 
317 	err = bus->methods->allocm(bus, &xfer->dmabuf, size);
318 	if (err)
319 		return (0);
320 	xfer->rqflags |= URQ_DEV_DMABUF;
321 	return (KERNADDR(&xfer->dmabuf));
322 }
323 
324 void
325 usbd_free_buffer(usbd_xfer_handle xfer)
326 {
327 #ifdef DIAGNOSTIC
328 	if (!(xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))) {
329 		printf("usbd_free_buffer: no buffer\n");
330 		return;
331 	}
332 #endif
333 	xfer->rqflags &= ~(URQ_DEV_DMABUF | URQ_AUTO_DMABUF);
334 	xfer->device->bus->methods->freem(xfer->device->bus, &xfer->dmabuf);
335 }
336 
337 void *
338 usbd_get_buffer(usbd_xfer_handle xfer)
339 {
340 	if (!(xfer->rqflags & URQ_DEV_DMABUF))
341 		return (0);
342 	return (KERNADDR(&xfer->dmabuf));
343 }
344 
345 usbd_xfer_handle
346 usbd_alloc_xfer(usbd_device_handle dev)
347 {
348 	usbd_xfer_handle xfer;
349 
350 	xfer = dev->bus->methods->allocx(dev->bus);
351 	if (xfer == NULL)
352 		return (NULL);
353 	xfer->device = dev;
354 	usb_callout_init(xfer->timeout_handle);
355 	DPRINTFN(5,("usbd_alloc_xfer() = %p\n", xfer));
356 	return (xfer);
357 }
358 
359 usbd_status
360 usbd_free_xfer(usbd_xfer_handle xfer)
361 {
362 	DPRINTFN(5,("usbd_free_xfer: %p\n", xfer));
363 	if (xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))
364 		usbd_free_buffer(xfer);
365 #if defined(__NetBSD__) && defined(DIAGNOSTIC)
366 	if (callout_pending(&xfer->timeout_handle)) {
367 		callout_stop(&xfer->timeout_handle);
368 		printf("usbd_free_xfer: timout_handle pending");
369 	}
370 #endif
371 	xfer->device->bus->methods->freex(xfer->device->bus, xfer);
372 	return (USBD_NORMAL_COMPLETION);
373 }
374 
375 void
376 usbd_setup_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
377 		usbd_private_handle priv, void *buffer, u_int32_t length,
378 		u_int16_t flags, u_int32_t timeout,
379 		usbd_callback callback)
380 {
381 	xfer->pipe = pipe;
382 	xfer->priv = priv;
383 	xfer->buffer = buffer;
384 	xfer->length = length;
385 	xfer->actlen = 0;
386 	xfer->flags = flags;
387 	xfer->timeout = timeout;
388 	xfer->status = USBD_NOT_STARTED;
389 	xfer->callback = callback;
390 	xfer->rqflags &= ~URQ_REQUEST;
391 	xfer->nframes = 0;
392 }
393 
394 void
395 usbd_setup_default_xfer(usbd_xfer_handle xfer, usbd_device_handle dev,
396 			usbd_private_handle priv, u_int32_t timeout,
397 			usb_device_request_t *req, void *buffer,
398 			u_int32_t length, u_int16_t flags,
399 			usbd_callback callback)
400 {
401 	xfer->pipe = dev->default_pipe;
402 	xfer->priv = priv;
403 	xfer->buffer = buffer;
404 	xfer->length = length;
405 	xfer->actlen = 0;
406 	xfer->flags = flags;
407 	xfer->timeout = timeout;
408 	xfer->status = USBD_NOT_STARTED;
409 	xfer->callback = callback;
410 	xfer->request = *req;
411 	xfer->rqflags |= URQ_REQUEST;
412 	xfer->nframes = 0;
413 }
414 
415 void
416 usbd_setup_isoc_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
417 		     usbd_private_handle priv, u_int16_t *frlengths,
418 		     u_int32_t nframes, u_int16_t flags, usbd_callback callback)
419 {
420 	xfer->pipe = pipe;
421 	xfer->priv = priv;
422 	xfer->buffer = 0;
423 	xfer->length = 0;
424 	xfer->actlen = 0;
425 	xfer->flags = flags;
426 	xfer->timeout = USBD_NO_TIMEOUT;
427 	xfer->status = USBD_NOT_STARTED;
428 	xfer->callback = callback;
429 	xfer->rqflags &= ~URQ_REQUEST;
430 	xfer->frlengths = frlengths;
431 	xfer->nframes = nframes;
432 }
433 
434 void
435 usbd_get_xfer_status(usbd_xfer_handle xfer, usbd_private_handle *priv,
436 		     void **buffer, u_int32_t *count, usbd_status *status)
437 {
438 	if (priv != NULL)
439 		*priv = xfer->priv;
440 	if (buffer != NULL)
441 		*buffer = xfer->buffer;
442 	if (count != NULL)
443 		*count = xfer->actlen;
444 	if (status != NULL)
445 		*status = xfer->status;
446 }
447 
448 usb_config_descriptor_t *
449 usbd_get_config_descriptor(usbd_device_handle dev)
450 {
451 #ifdef DIAGNOSTIC
452 	if (dev == NULL) {
453 		printf("usbd_get_config_descriptor: dev == NULL\n");
454 		return (NULL);
455 	}
456 #endif
457 	return (dev->cdesc);
458 }
459 
460 usb_interface_descriptor_t *
461 usbd_get_interface_descriptor(usbd_interface_handle iface)
462 {
463 #ifdef DIAGNOSTIC
464 	if (iface == NULL) {
465 		printf("usbd_get_interface_descriptor: dev == NULL\n");
466 		return (NULL);
467 	}
468 #endif
469 	return (iface->idesc);
470 }
471 
472 usb_device_descriptor_t *
473 usbd_get_device_descriptor(usbd_device_handle dev)
474 {
475 	return (&dev->ddesc);
476 }
477 
478 usb_endpoint_descriptor_t *
479 usbd_interface2endpoint_descriptor(usbd_interface_handle iface, u_int8_t index)
480 {
481 	if (index >= iface->idesc->bNumEndpoints)
482 		return (0);
483 	return (iface->endpoints[index].edesc);
484 }
485 
486 usbd_status
487 usbd_abort_pipe(usbd_pipe_handle pipe)
488 {
489 	usbd_status err;
490 	int s;
491 
492 #ifdef DIAGNOSTIC
493 	if (pipe == NULL) {
494 		printf("usbd_close_pipe: pipe==NULL\n");
495 		return (USBD_NORMAL_COMPLETION);
496 	}
497 #endif
498 	s = splusb();
499 	err = usbd_ar_pipe(pipe);
500 	splx(s);
501 	return (err);
502 }
503 
504 usbd_status
505 usbd_clear_endpoint_stall(usbd_pipe_handle pipe)
506 {
507 	usbd_device_handle dev = pipe->device;
508 	usb_device_request_t req;
509 	usbd_status err;
510 
511 	DPRINTFN(8, ("usbd_clear_endpoint_stall\n"));
512 
513 	/*
514 	 * Clearing en endpoint stall resets the enpoint toggle, so
515 	 * do the same to the HC toggle.
516 	 */
517 	pipe->methods->cleartoggle(pipe);
518 
519 	req.bmRequestType = UT_WRITE_ENDPOINT;
520 	req.bRequest = UR_CLEAR_FEATURE;
521 	USETW(req.wValue, UF_ENDPOINT_HALT);
522 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
523 	USETW(req.wLength, 0);
524 	err = usbd_do_request(dev, &req, 0);
525 #if 0
526 XXX should we do this?
527 	if (!err) {
528 		pipe->state = USBD_PIPE_ACTIVE;
529 		/* XXX activate pipe */
530 	}
531 #endif
532 	return (err);
533 }
534 
535 usbd_status
536 usbd_clear_endpoint_stall_async(usbd_pipe_handle pipe)
537 {
538 	usbd_device_handle dev = pipe->device;
539 	usb_device_request_t req;
540 	usbd_status err;
541 
542 	pipe->methods->cleartoggle(pipe);
543 
544 	req.bmRequestType = UT_WRITE_ENDPOINT;
545 	req.bRequest = UR_CLEAR_FEATURE;
546 	USETW(req.wValue, UF_ENDPOINT_HALT);
547 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
548 	USETW(req.wLength, 0);
549 	err = usbd_do_request_async(dev, &req, 0);
550 	return (err);
551 }
552 
553 void usbd_clear_endpoint_toggle(usbd_pipe_handle pipe); /* XXXXX */
554 void
555 usbd_clear_endpoint_toggle(usbd_pipe_handle pipe)
556 {
557 	pipe->methods->cleartoggle(pipe);
558 }
559 
560 usbd_status
561 usbd_endpoint_count(usbd_interface_handle iface, u_int8_t *count)
562 {
563 #ifdef DIAGNOSTIC
564 	if (iface == NULL || iface->idesc == NULL) {
565 		printf("usbd_endpoint_count: NULL pointer\n");
566 		return (USBD_INVAL);
567 	}
568 #endif
569 	*count = iface->idesc->bNumEndpoints;
570 	return (USBD_NORMAL_COMPLETION);
571 }
572 
573 usbd_status
574 usbd_interface_count(usbd_device_handle dev, u_int8_t *count)
575 {
576 	if (dev->cdesc == NULL)
577 		return (USBD_NOT_CONFIGURED);
578 	*count = dev->cdesc->bNumInterface;
579 	return (USBD_NORMAL_COMPLETION);
580 }
581 
582 usbd_status
583 usbd_interface2device_handle(usbd_interface_handle iface,
584 			     usbd_device_handle *dev)
585 {
586 	*dev = iface->device;
587 	return (USBD_NORMAL_COMPLETION);
588 }
589 
590 usbd_status
591 usbd_device2interface_handle(usbd_device_handle dev,
592 			     u_int8_t ifaceno, usbd_interface_handle *iface)
593 {
594 	if (dev->cdesc == NULL)
595 		return (USBD_NOT_CONFIGURED);
596 	if (ifaceno >= dev->cdesc->bNumInterface)
597 		return (USBD_INVAL);
598 	*iface = &dev->ifaces[ifaceno];
599 	return (USBD_NORMAL_COMPLETION);
600 }
601 
602 usbd_device_handle
603 usbd_pipe2device_handle(usbd_pipe_handle pipe)
604 {
605 	return (pipe->device);
606 }
607 
608 /* XXXX use altno */
609 usbd_status
610 usbd_set_interface(usbd_interface_handle iface, int altidx)
611 {
612 	usb_device_request_t req;
613 	usbd_status err;
614 	void *endpoints;
615 
616 	if (LIST_FIRST(&iface->pipes) != 0)
617 		return (USBD_IN_USE);
618 
619 	endpoints = iface->endpoints;
620 	err = usbd_fill_iface_data(iface->device, iface->index, altidx);
621 	if (err)
622 		return (err);
623 
624 	/* new setting works, we can free old endpoints */
625 	if (endpoints != NULL)
626 		free(endpoints, M_USB);
627 
628 #ifdef DIAGNOSTIC
629 	if (iface->idesc == NULL) {
630 		printf("usbd_set_interface: NULL pointer\n");
631 		return (USBD_INVAL);
632 	}
633 #endif
634 
635 	req.bmRequestType = UT_WRITE_INTERFACE;
636 	req.bRequest = UR_SET_INTERFACE;
637 	USETW(req.wValue, iface->idesc->bAlternateSetting);
638 	USETW(req.wIndex, iface->idesc->bInterfaceNumber);
639 	USETW(req.wLength, 0);
640 	return (usbd_do_request(iface->device, &req, 0));
641 }
642 
643 int
644 usbd_get_no_alts(usb_config_descriptor_t *cdesc, int ifaceno)
645 {
646 	char *p = (char *)cdesc;
647 	char *end = p + UGETW(cdesc->wTotalLength);
648 	usb_interface_descriptor_t *d;
649 	int n;
650 
651 	for (n = 0; p < end; p += d->bLength) {
652 		d = (usb_interface_descriptor_t *)p;
653 		if (p + d->bLength <= end &&
654 		    d->bDescriptorType == UDESC_INTERFACE &&
655 		    d->bInterfaceNumber == ifaceno)
656 			n++;
657 	}
658 	return (n);
659 }
660 
661 int
662 usbd_get_interface_altindex(usbd_interface_handle iface)
663 {
664 	return (iface->altindex);
665 }
666 
667 usbd_status
668 usbd_get_interface(usbd_interface_handle iface, u_int8_t *aiface)
669 {
670 	usb_device_request_t req;
671 
672 	req.bmRequestType = UT_READ_INTERFACE;
673 	req.bRequest = UR_GET_INTERFACE;
674 	USETW(req.wValue, 0);
675 	USETW(req.wIndex, iface->idesc->bInterfaceNumber);
676 	USETW(req.wLength, 1);
677 	return (usbd_do_request(iface->device, &req, aiface));
678 }
679 
680 /*** Internal routines ***/
681 
682 /* Dequeue all pipe operations, called at splusb(). */
683 Static usbd_status
684 usbd_ar_pipe(usbd_pipe_handle pipe)
685 {
686 	usbd_xfer_handle xfer;
687 
688 	SPLUSBCHECK;
689 
690 	DPRINTFN(2,("usbd_ar_pipe: pipe=%p\n", pipe));
691 #ifdef USB_DEBUG
692 	if (usbdebug > 5)
693 		usbd_dump_queue(pipe);
694 #endif
695 	pipe->repeat = 0;
696 	pipe->aborting = 1;
697 	while ((xfer = SIMPLEQ_FIRST(&pipe->queue)) != NULL) {
698 		DPRINTFN(2,("usbd_ar_pipe: pipe=%p xfer=%p (methods=%p)\n",
699 			    pipe, xfer, pipe->methods));
700 		/* Make the HC abort it (and invoke the callback). */
701 		pipe->methods->abort(xfer);
702 		/* XXX only for non-0 usbd_clear_endpoint_stall(pipe); */
703 	}
704 	pipe->aborting = 0;
705 	return (USBD_NORMAL_COMPLETION);
706 }
707 
708 /* Called at splusb() */
709 void
710 usb_transfer_complete(usbd_xfer_handle xfer)
711 {
712 	usbd_pipe_handle pipe = xfer->pipe;
713 	usb_dma_t *dmap = &xfer->dmabuf;
714 	int repeat = pipe->repeat;
715 	int polling;
716 
717 	SPLUSBCHECK;
718 
719 	DPRINTFN(5, ("usb_transfer_complete: pipe=%p xfer=%p status=%d "
720 		     "actlen=%d\n", pipe, xfer, xfer->status, xfer->actlen));
721 
722 #ifdef DIAGNOSTIC
723 	if (pipe == NULL) {
724 		printf("usbd_transfer_cb: pipe==0, xfer=%p\n", xfer);
725 		return;
726 	}
727 #endif
728 	polling = pipe->device->bus->use_polling;
729 	/* XXXX */
730 	if (polling)
731 		pipe->running = 0;
732 
733 	if (!(xfer->flags & USBD_NO_COPY) && xfer->actlen != 0 &&
734 	    usbd_xfer_isread(xfer)) {
735 #ifdef DIAGNOSTIC
736 		if (xfer->actlen > xfer->length) {
737 			printf("usb_transfer_complete: actlen > len %d > %d\n",
738 			       xfer->actlen, xfer->length);
739 			xfer->actlen = xfer->length;
740 		}
741 #endif
742 		memcpy(xfer->buffer, KERNADDR(dmap), xfer->actlen);
743 	}
744 
745 	/* if we allocated the buffer in usbd_transfer() we free it here. */
746 	if (xfer->rqflags & URQ_AUTO_DMABUF) {
747 		if (!repeat) {
748 			struct usbd_bus *bus = pipe->device->bus;
749 			bus->methods->freem(bus, dmap);
750 			xfer->rqflags &= ~URQ_AUTO_DMABUF;
751 		}
752 	}
753 
754 	if (!repeat) {
755 		/* Remove request from queue. */
756 #ifdef DIAGNOSTIC
757 		if (xfer != SIMPLEQ_FIRST(&pipe->queue))
758 			printf("usb_transfer_complete: bad dequeue %p != %p\n",
759 			       xfer, SIMPLEQ_FIRST(&pipe->queue));
760 #endif
761 		SIMPLEQ_REMOVE_HEAD(&pipe->queue, xfer, next);
762 	}
763 	DPRINTFN(5,("usb_transfer_complete: repeat=%d new head=%p\n",
764 		    repeat, SIMPLEQ_FIRST(&pipe->queue)));
765 
766 	/* Count completed transfers. */
767 	++pipe->device->bus->stats.requests
768 		[pipe->endpoint->edesc->bmAttributes & UE_XFERTYPE];
769 
770 	xfer->done = 1;
771 	if (!xfer->status && xfer->actlen < xfer->length &&
772 	    !(xfer->flags & USBD_SHORT_XFER_OK)) {
773 		DPRINTFN(-1,("usbd_transfer_cb: short transfer %d<%d\n",
774 			     xfer->actlen, xfer->length));
775 		xfer->status = USBD_SHORT_XFER;
776 	}
777 
778 	if (xfer->callback)
779 		xfer->callback(xfer, xfer->priv, xfer->status);
780 
781 #ifdef DIAGNOSTIC
782 	if (pipe->methods->done != NULL)
783 		pipe->methods->done(xfer);
784 	else
785 		printf("usb_transfer_complete: pipe->methods->done == NULL\n");
786 #else
787 	pipe->methods->done(xfer);
788 #endif
789 
790 	if ((xfer->flags & USBD_SYNCHRONOUS) && !polling)
791 		wakeup(xfer);
792 
793 	if (!repeat) {
794 		/* XXX should we stop the queue on all errors? */
795 		if ((xfer->status == USBD_CANCELLED ||
796 		     xfer->status == USBD_TIMEOUT) &&
797 		    pipe->iface != NULL)		/* not control pipe */
798 			pipe->running = 0;
799 		else
800 			usbd_start_next(pipe);
801 	}
802 }
803 
804 usbd_status
805 usb_insert_transfer(usbd_xfer_handle xfer)
806 {
807 	usbd_pipe_handle pipe = xfer->pipe;
808 	usbd_status err;
809 	int s;
810 
811 	DPRINTFN(5,("usb_insert_transfer: pipe=%p running=%d timeout=%d\n",
812 		    pipe, pipe->running, xfer->timeout));
813 	s = splusb();
814 	SIMPLEQ_INSERT_TAIL(&pipe->queue, xfer, next);
815 	if (pipe->running)
816 		err = USBD_IN_PROGRESS;
817 	else {
818 		pipe->running = 1;
819 		err = USBD_NORMAL_COMPLETION;
820 	}
821 	splx(s);
822 	return (err);
823 }
824 
825 /* Called at splusb() */
826 void
827 usbd_start_next(usbd_pipe_handle pipe)
828 {
829 	usbd_xfer_handle xfer;
830 	usbd_status err;
831 
832 	SPLUSBCHECK;
833 
834 #ifdef DIAGNOSTIC
835 	if (pipe == NULL) {
836 		printf("usbd_start_next: pipe == NULL\n");
837 		return;
838 	}
839 	if (pipe->methods == NULL || pipe->methods->start == NULL) {
840 		printf("usbd_start_next: pipe=%p no start method\n", pipe);
841 		return;
842 	}
843 #endif
844 
845 	/* Get next request in queue. */
846 	xfer = SIMPLEQ_FIRST(&pipe->queue);
847 	DPRINTFN(5, ("usbd_start_next: pipe=%p, xfer=%p\n", pipe, xfer));
848 	if (xfer == NULL) {
849 		pipe->running = 0;
850 	} else {
851 		err = pipe->methods->start(xfer);
852 		if (err != USBD_IN_PROGRESS) {
853 			printf("usbd_start_next: error=%d\n", err);
854 			pipe->running = 0;
855 			/* XXX do what? */
856 		}
857 	}
858 }
859 
860 usbd_status
861 usbd_do_request(usbd_device_handle dev, usb_device_request_t *req, void *data)
862 {
863 	return (usbd_do_request_flags(dev, req, data, 0, 0));
864 }
865 
866 usbd_status
867 usbd_do_request_flags(usbd_device_handle dev, usb_device_request_t *req,
868 		      void *data, u_int16_t flags, int *actlen)
869 {
870 	return (usbd_do_request_flags_pipe(dev, dev->default_pipe, req,
871 					   data, flags, actlen));
872 }
873 
874 usbd_status
875 usbd_do_request_flags_pipe(usbd_device_handle dev, usbd_pipe_handle pipe,
876 	usb_device_request_t *req, void *data, u_int16_t flags, int *actlen)
877 {
878 	usbd_xfer_handle xfer;
879 	usbd_status err;
880 
881 #ifdef DIAGNOSTIC
882 #if defined(__i386__) && defined(__FreeBSD__)
883 	KASSERT(intr_nesting_level == 0,
884 	       	("usbd_do_request: in interrupt context"));
885 #endif
886 	if (dev->bus->intr_context) {
887 		printf("usbd_do_request: not in process context\n");
888 		return (USBD_INVAL);
889 	}
890 #endif
891 
892 	xfer = usbd_alloc_xfer(dev);
893 	if (xfer == NULL)
894 		return (USBD_NOMEM);
895 	usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT, req,
896 				data, UGETW(req->wLength), flags, 0);
897 	xfer->pipe = pipe;
898 	err = usbd_sync_transfer(xfer);
899 #if defined(USB_DEBUG) || defined(DIAGNOSTIC)
900 	if (xfer->actlen > xfer->length)
901 		DPRINTF(("usbd_do_request: overrun addr=%d type=0x%02x req=0x"
902 			 "%02x val=%d index=%d rlen=%d length=%d actlen=%d\n",
903 			 dev->address, xfer->request.bmRequestType,
904 			 xfer->request.bRequest, UGETW(xfer->request.wValue),
905 			 UGETW(xfer->request.wIndex),
906 			 UGETW(xfer->request.wLength),
907 			 xfer->length, xfer->actlen));
908 #endif
909 	if (actlen != NULL)
910 		*actlen = xfer->actlen;
911 	if (err == USBD_STALLED) {
912 		/*
913 		 * The control endpoint has stalled.  Control endpoints
914 		 * should not halt, but some may do so anyway so clear
915 		 * any halt condition.
916 		 */
917 		usb_device_request_t treq;
918 		usb_status_t status;
919 		u_int16_t s;
920 		usbd_status nerr;
921 
922 		treq.bmRequestType = UT_READ_ENDPOINT;
923 		treq.bRequest = UR_GET_STATUS;
924 		USETW(treq.wValue, 0);
925 		USETW(treq.wIndex, 0);
926 		USETW(treq.wLength, sizeof(usb_status_t));
927 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
928 					   &treq, &status,sizeof(usb_status_t),
929 					   0, 0);
930 		nerr = usbd_sync_transfer(xfer);
931 		if (nerr)
932 			goto bad;
933 		s = UGETW(status.wStatus);
934 		DPRINTF(("usbd_do_request: status = 0x%04x\n", s));
935 		if (!(s & UES_HALT))
936 			goto bad;
937 		treq.bmRequestType = UT_WRITE_ENDPOINT;
938 		treq.bRequest = UR_CLEAR_FEATURE;
939 		USETW(treq.wValue, UF_ENDPOINT_HALT);
940 		USETW(treq.wIndex, 0);
941 		USETW(treq.wLength, 0);
942 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
943 					   &treq, &status, 0, 0, 0);
944 		nerr = usbd_sync_transfer(xfer);
945 		if (nerr)
946 			goto bad;
947 	}
948 
949  bad:
950 	usbd_free_xfer(xfer);
951 	return (err);
952 }
953 
954 void
955 usbd_do_request_async_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
956 			 usbd_status status)
957 {
958 #if defined(USB_DEBUG) || defined(DIAGNOSTIC)
959 	if (xfer->actlen > xfer->length)
960 		DPRINTF(("usbd_do_request: overrun addr=%d type=0x%02x req=0x"
961 			 "%02x val=%d index=%d rlen=%d length=%d actlen=%d\n",
962 			 xfer->pipe->device->address,
963 			 xfer->request.bmRequestType,
964 			 xfer->request.bRequest, UGETW(xfer->request.wValue),
965 			 UGETW(xfer->request.wIndex),
966 			 UGETW(xfer->request.wLength),
967 			 xfer->length, xfer->actlen));
968 #endif
969 	usbd_free_xfer(xfer);
970 }
971 
972 /*
973  * Execute a request without waiting for completion.
974  * Can be used from interrupt context.
975  */
976 usbd_status
977 usbd_do_request_async(usbd_device_handle dev, usb_device_request_t *req,
978 		      void *data)
979 {
980 	usbd_xfer_handle xfer;
981 	usbd_status err;
982 
983 	xfer = usbd_alloc_xfer(dev);
984 	if (xfer == NULL)
985 		return (USBD_NOMEM);
986 	usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT, req,
987 	    data, UGETW(req->wLength), 0, usbd_do_request_async_cb);
988 	err = usbd_transfer(xfer);
989 	if (err != USBD_IN_PROGRESS) {
990 		usbd_free_xfer(xfer);
991 		return (err);
992 	}
993 	return (USBD_NORMAL_COMPLETION);
994 }
995 
996 const struct usbd_quirks *
997 usbd_get_quirks(usbd_device_handle dev)
998 {
999 #ifdef DIAGNOSTIC
1000 	if (dev == NULL) {
1001 		printf("usbd_get_quirks: dev == NULL\n");
1002 		return 0;
1003 	}
1004 #endif
1005 	return (dev->quirks);
1006 }
1007 
1008 /* XXX do periodic free() of free list */
1009 
1010 /*
1011  * Called from keyboard driver when in polling mode.
1012  */
1013 void
1014 usbd_dopoll(usbd_interface_handle iface)
1015 {
1016 	iface->device->bus->methods->do_poll(iface->device->bus);
1017 }
1018 
1019 void
1020 usbd_set_polling(usbd_device_handle dev, int on)
1021 {
1022 	if (on)
1023 		dev->bus->use_polling++;
1024 	else
1025 		dev->bus->use_polling--;
1026 }
1027 
1028 
1029 usb_endpoint_descriptor_t *
1030 usbd_get_endpoint_descriptor(usbd_interface_handle iface, u_int8_t address)
1031 {
1032 	struct usbd_endpoint *ep;
1033 	int i;
1034 
1035 	for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
1036 		ep = &iface->endpoints[i];
1037 		if (ep->edesc->bEndpointAddress == address)
1038 			return (iface->endpoints[i].edesc);
1039 	}
1040 	return (0);
1041 }
1042 
1043 /*
1044  * usbd_ratecheck() can limit the number of error messages that occurs.
1045  * When a device is unplugged it may take up to 0.25s for the hub driver
1046  * to notice it.  If the driver continuosly tries to do I/O operations
1047  * this can generate a large number of messages.
1048  */
1049 int
1050 usbd_ratecheck(struct timeval *last)
1051 {
1052 	static struct timeval errinterval = { 0, 250000 }; /* 0.25 s*/
1053 
1054 	return (ratecheck(last, &errinterval));
1055 }
1056 
1057 #if defined(__FreeBSD__)
1058 int
1059 usbd_driver_load(module_t mod, int what, void *arg)
1060 {
1061 	/* XXX should implement something like a function that removes all generic devices */
1062 
1063  	return (0);
1064 }
1065 
1066 #endif
1067