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