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