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