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