xref: /openbsd-src/sys/dev/usb/usbdi.c (revision 505ee9ea3b177e2387d907a91ca7da069f3f14d8)
1 /*	$OpenBSD: usbdi.c,v 1.106 2020/04/03 20:11:47 patrick 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, 0, &xfer->dmabuf);
309 		if (err)
310 			return (err);
311 		xfer->rqflags |= URQ_AUTO_DMABUF;
312 	}
313 
314 	if (!usbd_xfer_isread(xfer) && (xfer->flags & USBD_NO_COPY) == 0)
315 		memcpy(KERNADDR(&xfer->dmabuf, 0), xfer->buffer,
316 		    xfer->length);
317 
318 	usb_tap(bus, xfer, USBTAP_DIR_OUT);
319 
320 	err = pipe->methods->transfer(xfer);
321 
322 	if (err != USBD_IN_PROGRESS && err != USBD_NORMAL_COMPLETION) {
323 		/* The transfer has not been queued, so free buffer. */
324 		if (xfer->rqflags & URQ_AUTO_DMABUF) {
325 			usb_freemem(bus, &xfer->dmabuf);
326 			xfer->rqflags &= ~URQ_AUTO_DMABUF;
327 		}
328 	}
329 
330 	if (!(xfer->flags & USBD_SYNCHRONOUS))
331 		return (err);
332 
333 	/* Sync transfer, wait for completion. */
334 	if (err != USBD_IN_PROGRESS)
335 		return (err);
336 
337 	s = splusb();
338 	if (polling) {
339 		int timo;
340 
341 		for (timo = xfer->timeout; timo >= 0; timo--) {
342 			usb_delay_ms(bus, 1);
343 			if (bus->dying) {
344 				xfer->status = USBD_IOERROR;
345 				usb_transfer_complete(xfer);
346 				break;
347 			}
348 
349 			usbd_dopoll(pipe->device);
350 			if (xfer->done)
351 				break;
352 		}
353 
354 		if (timo < 0) {
355 			xfer->status = USBD_TIMEOUT;
356 			usb_transfer_complete(xfer);
357 		}
358 	} else {
359 		while (!xfer->done) {
360 			flags = PRIBIO|(xfer->flags & USBD_CATCH ? PCATCH : 0);
361 
362 			err = tsleep_nsec(xfer, flags, "usbsyn", INFSLP);
363 			if (err && !xfer->done) {
364 				usbd_abort_pipe(pipe);
365 				if (err == EINTR)
366 					xfer->status = USBD_INTERRUPTED;
367 				else
368 					xfer->status = USBD_TIMEOUT;
369 			}
370 		}
371 	}
372 	splx(s);
373 	return (xfer->status);
374 }
375 
376 void *
377 usbd_alloc_buffer(struct usbd_xfer *xfer, u_int32_t size)
378 {
379 	struct usbd_bus *bus = xfer->device->bus;
380 	usbd_status err;
381 
382 #ifdef DIAGNOSTIC
383 	if (xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))
384 		printf("usbd_alloc_buffer: xfer already has a buffer\n");
385 #endif
386 	err = usb_allocmem(bus, size, 0, 0, &xfer->dmabuf);
387 	if (err)
388 		return (NULL);
389 	xfer->rqflags |= URQ_DEV_DMABUF;
390 	return (KERNADDR(&xfer->dmabuf, 0));
391 }
392 
393 void
394 usbd_free_buffer(struct usbd_xfer *xfer)
395 {
396 #ifdef DIAGNOSTIC
397 	if (!(xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))) {
398 		printf("usbd_free_buffer: no buffer\n");
399 		return;
400 	}
401 #endif
402 	xfer->rqflags &= ~(URQ_DEV_DMABUF | URQ_AUTO_DMABUF);
403 	usb_freemem(xfer->device->bus, &xfer->dmabuf);
404 }
405 
406 struct usbd_xfer *
407 usbd_alloc_xfer(struct usbd_device *dev)
408 {
409 	struct usbd_xfer *xfer;
410 
411 	xfer = dev->bus->methods->allocx(dev->bus);
412 	if (xfer == NULL)
413 		return (NULL);
414 #ifdef DIAGNOSTIC
415 	xfer->busy_free = XFER_FREE;
416 #endif
417 	xfer->device = dev;
418 	timeout_set(&xfer->timeout_handle, NULL, NULL);
419 	DPRINTFN(5,("usbd_alloc_xfer() = %p\n", xfer));
420 	return (xfer);
421 }
422 
423 void
424 usbd_free_xfer(struct usbd_xfer *xfer)
425 {
426 	DPRINTFN(5,("%s: %p\n", __func__, xfer));
427 	if (xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))
428 		usbd_free_buffer(xfer);
429 #ifdef DIAGNOSTIC
430 	if (xfer->busy_free != XFER_FREE) {
431 		printf("%s: xfer=%p not free\n", __func__, xfer);
432 		return;
433 	}
434 #endif
435 	xfer->device->bus->methods->freex(xfer->device->bus, xfer);
436 }
437 
438 void
439 usbd_setup_xfer(struct usbd_xfer *xfer, struct usbd_pipe *pipe,
440     void *priv, void *buffer, u_int32_t length, u_int16_t flags,
441     u_int32_t timeout, usbd_callback callback)
442 {
443 	xfer->pipe = pipe;
444 	xfer->priv = priv;
445 	xfer->buffer = buffer;
446 	xfer->length = length;
447 	xfer->actlen = 0;
448 	xfer->flags = flags;
449 	xfer->timeout = timeout;
450 	xfer->status = USBD_NOT_STARTED;
451 	xfer->callback = callback;
452 	xfer->rqflags &= ~URQ_REQUEST;
453 	xfer->nframes = 0;
454 }
455 
456 void
457 usbd_setup_default_xfer(struct usbd_xfer *xfer, struct usbd_device *dev,
458     void *priv, u_int32_t timeout, usb_device_request_t *req,
459     void *buffer, u_int32_t length, u_int16_t flags, usbd_callback callback)
460 {
461 	xfer->pipe = dev->default_pipe;
462 	xfer->priv = priv;
463 	xfer->buffer = buffer;
464 	xfer->length = length;
465 	xfer->actlen = 0;
466 	xfer->flags = flags;
467 	xfer->timeout = timeout;
468 	xfer->status = USBD_NOT_STARTED;
469 	xfer->callback = callback;
470 	xfer->request = *req;
471 	xfer->rqflags |= URQ_REQUEST;
472 	xfer->nframes = 0;
473 }
474 
475 void
476 usbd_setup_isoc_xfer(struct usbd_xfer *xfer, struct usbd_pipe *pipe,
477     void *priv, u_int16_t *frlengths, u_int32_t nframes,
478     u_int16_t flags, usbd_callback callback)
479 {
480 	int i;
481 
482 	xfer->pipe = pipe;
483 	xfer->priv = priv;
484 	xfer->buffer = 0;
485 	xfer->length = 0;
486 	for (i = 0; i < nframes; i++)
487 		xfer->length += frlengths[i];
488 	xfer->actlen = 0;
489 	xfer->flags = flags;
490 	xfer->timeout = USBD_NO_TIMEOUT;
491 	xfer->status = USBD_NOT_STARTED;
492 	xfer->callback = callback;
493 	xfer->rqflags &= ~URQ_REQUEST;
494 	xfer->frlengths = frlengths;
495 	xfer->nframes = nframes;
496 }
497 
498 void
499 usbd_get_xfer_status(struct usbd_xfer *xfer, void **priv,
500     void **buffer, u_int32_t *count, usbd_status *status)
501 {
502 	if (priv != NULL)
503 		*priv = xfer->priv;
504 	if (buffer != NULL)
505 		*buffer = xfer->buffer;
506 	if (count != NULL)
507 		*count = xfer->actlen;
508 	if (status != NULL)
509 		*status = xfer->status;
510 }
511 
512 usb_config_descriptor_t *
513 usbd_get_config_descriptor(struct usbd_device *dev)
514 {
515 #ifdef DIAGNOSTIC
516 	if (dev == NULL) {
517 		printf("usbd_get_config_descriptor: dev == NULL\n");
518 		return (NULL);
519 	}
520 #endif
521 	return (dev->cdesc);
522 }
523 
524 usb_interface_descriptor_t *
525 usbd_get_interface_descriptor(struct usbd_interface *iface)
526 {
527 #ifdef DIAGNOSTIC
528 	if (iface == NULL) {
529 		printf("usbd_get_interface_descriptor: dev == NULL\n");
530 		return (NULL);
531 	}
532 #endif
533 	return (iface->idesc);
534 }
535 
536 usb_device_descriptor_t *
537 usbd_get_device_descriptor(struct usbd_device *dev)
538 {
539 	return (&dev->ddesc);
540 }
541 
542 usb_endpoint_descriptor_t *
543 usbd_interface2endpoint_descriptor(struct usbd_interface *iface, u_int8_t index)
544 {
545 	if (index >= iface->idesc->bNumEndpoints)
546 		return (0);
547 	return (iface->endpoints[index].edesc);
548 }
549 
550 void
551 usbd_abort_pipe(struct usbd_pipe *pipe)
552 {
553 	struct usbd_xfer *xfer;
554 	int s;
555 
556 #ifdef DIAGNOSTIC
557 	if (pipe == NULL) {
558 		printf("usbd_abort_pipe: pipe==NULL\n");
559 		return;
560 	}
561 #endif
562 	s = splusb();
563 	DPRINTFN(2,("%s: pipe=%p\n", __func__, pipe));
564 #ifdef USB_DEBUG
565 	if (usbdebug > 5)
566 		usbd_dump_queue(pipe);
567 #endif
568 	pipe->repeat = 0;
569 	pipe->aborting = 1;
570 	while ((xfer = SIMPLEQ_FIRST(&pipe->queue)) != NULL) {
571 		DPRINTFN(2,("%s: pipe=%p xfer=%p (methods=%p)\n", __func__,
572 		    pipe, xfer, pipe->methods));
573 		/* Make the HC abort it (and invoke the callback). */
574 		pipe->methods->abort(xfer);
575 		/* XXX only for non-0 usbd_clear_endpoint_stall(pipe); */
576 	}
577 	pipe->aborting = 0;
578 	splx(s);
579 }
580 
581 usbd_status
582 usbd_clear_endpoint_stall(struct usbd_pipe *pipe)
583 {
584 	struct usbd_device *dev = pipe->device;
585 	usb_device_request_t req;
586 	usbd_status err;
587 
588 	DPRINTFN(8, ("usbd_clear_endpoint_stall\n"));
589 
590 	/*
591 	 * Clearing en endpoint stall resets the endpoint toggle, so
592 	 * do the same to the HC toggle.
593 	 */
594 	usbd_clear_endpoint_toggle(pipe);
595 
596 	req.bmRequestType = UT_WRITE_ENDPOINT;
597 	req.bRequest = UR_CLEAR_FEATURE;
598 	USETW(req.wValue, UF_ENDPOINT_HALT);
599 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
600 	USETW(req.wLength, 0);
601 	err = usbd_do_request(dev, &req, 0);
602 
603 	return (err);
604 }
605 
606 usbd_status
607 usbd_clear_endpoint_stall_async(struct usbd_pipe *pipe)
608 {
609 	struct usbd_device *dev = pipe->device;
610 	struct usbd_xfer *xfer;
611 	usb_device_request_t req;
612 	usbd_status err;
613 
614 	usbd_clear_endpoint_toggle(pipe);
615 
616 	req.bmRequestType = UT_WRITE_ENDPOINT;
617 	req.bRequest = UR_CLEAR_FEATURE;
618 	USETW(req.wValue, UF_ENDPOINT_HALT);
619 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
620 	USETW(req.wLength, 0);
621 
622 	xfer = usbd_alloc_xfer(dev);
623 	if (xfer == NULL)
624 		return (USBD_NOMEM);
625 
626 	err = usbd_request_async(xfer, &req, NULL, NULL);
627 	return (err);
628 }
629 
630 void
631 usbd_clear_endpoint_toggle(struct usbd_pipe *pipe)
632 {
633 	if (pipe->methods->cleartoggle != NULL)
634 		pipe->methods->cleartoggle(pipe);
635 }
636 
637 usbd_status
638 usbd_device2interface_handle(struct usbd_device *dev, u_int8_t ifaceno,
639     struct usbd_interface **iface)
640 {
641 	if (dev->cdesc == NULL)
642 		return (USBD_NOT_CONFIGURED);
643 	if (ifaceno >= dev->cdesc->bNumInterface)
644 		return (USBD_INVAL);
645 	*iface = &dev->ifaces[ifaceno];
646 	return (USBD_NORMAL_COMPLETION);
647 }
648 
649 /* XXXX use altno */
650 usbd_status
651 usbd_set_interface(struct usbd_interface *iface, int altidx)
652 {
653 	usb_device_request_t req;
654 	usbd_status err;
655 	struct usbd_endpoint *endpoints;
656 	int nendpt;
657 
658 	if (LIST_FIRST(&iface->pipes) != 0)
659 		return (USBD_IN_USE);
660 
661 	endpoints = iface->endpoints;
662 	nendpt = iface->nendpt;
663 	err = usbd_fill_iface_data(iface->device, iface->index, altidx);
664 	if (err)
665 		return (err);
666 
667 	/* new setting works, we can free old endpoints */
668 	free(endpoints, M_USB, nendpt * sizeof(*endpoints));
669 
670 #ifdef DIAGNOSTIC
671 	if (iface->idesc == NULL) {
672 		printf("usbd_set_interface: NULL pointer\n");
673 		return (USBD_INVAL);
674 	}
675 #endif
676 
677 	req.bmRequestType = UT_WRITE_INTERFACE;
678 	req.bRequest = UR_SET_INTERFACE;
679 	USETW(req.wValue, iface->idesc->bAlternateSetting);
680 	USETW(req.wIndex, iface->idesc->bInterfaceNumber);
681 	USETW(req.wLength, 0);
682 	return (usbd_do_request(iface->device, &req, 0));
683 }
684 
685 int
686 usbd_get_no_alts(usb_config_descriptor_t *cdesc, int ifaceno)
687 {
688 	char *p = (char *)cdesc;
689 	char *end = p + UGETW(cdesc->wTotalLength);
690 	usb_interface_descriptor_t *d;
691 	int n;
692 
693 	for (n = 0; p < end; p += d->bLength) {
694 		d = (usb_interface_descriptor_t *)p;
695 		if (p + d->bLength <= end &&
696 		    d->bDescriptorType == UDESC_INTERFACE &&
697 		    d->bInterfaceNumber == ifaceno)
698 			n++;
699 	}
700 	return (n);
701 }
702 
703 int
704 usbd_get_interface_altindex(struct usbd_interface *iface)
705 {
706 	return (iface->altindex);
707 }
708 
709 /*** Internal routines ***/
710 
711 /* Called at splusb() */
712 void
713 usb_transfer_complete(struct usbd_xfer *xfer)
714 {
715 	struct usbd_pipe *pipe = xfer->pipe;
716 	struct usbd_bus *bus = pipe->device->bus;
717 	int polling = bus->use_polling;
718 	int status, flags;
719 
720 #if 0
721 	/* XXX ohci_intr1() calls usb_transfer_complete() for RHSC. */
722 	splsoftassert(IPL_SOFTUSB);
723 #endif
724 
725 	DPRINTFN(5, ("usb_transfer_complete: pipe=%p xfer=%p status=%d "
726 		     "actlen=%d\n", pipe, xfer, xfer->status, xfer->actlen));
727 #ifdef DIAGNOSTIC
728 	if (xfer->busy_free != XFER_ONQU) {
729 		printf("%s: xfer=%p not on queue\n", __func__, xfer);
730 		return;
731 	}
732 #endif
733 
734 	/* XXXX */
735 	if (polling)
736 		pipe->running = 0;
737 
738 #ifdef DIAGNOSTIC
739 	if (xfer->actlen > xfer->length) {
740 		printf("%s: actlen > len %u > %u\n", __func__, xfer->actlen,
741 		    xfer->length);
742 		xfer->actlen = xfer->length;
743 	}
744 #endif
745 
746 	if (usbd_xfer_isread(xfer) && xfer->actlen != 0 &&
747 	    (xfer->flags & USBD_NO_COPY) == 0)
748 		memcpy(xfer->buffer, KERNADDR(&xfer->dmabuf, 0),
749 		    xfer->actlen);
750 
751 	/* if we allocated the buffer in usbd_transfer() we free it here. */
752 	if (xfer->rqflags & URQ_AUTO_DMABUF) {
753 		if (!pipe->repeat) {
754 			usb_freemem(bus, &xfer->dmabuf);
755 			xfer->rqflags &= ~URQ_AUTO_DMABUF;
756 		}
757 	}
758 
759 	if (!pipe->repeat) {
760 		/* Remove request from queue. */
761 		KASSERT(xfer == SIMPLEQ_FIRST(&pipe->queue));
762 		SIMPLEQ_REMOVE_HEAD(&pipe->queue, next);
763 #ifdef DIAGNOSTIC
764 		xfer->busy_free = XFER_FREE;
765 #endif
766 	}
767 	DPRINTFN(5,("%s: repeat=%d new head=%p\n", __func__,
768 	    pipe->repeat, SIMPLEQ_FIRST(&pipe->queue)));
769 
770 	/* Count completed transfers. */
771 	++bus->stats.uds_requests
772 		[UE_GET_XFERTYPE(pipe->endpoint->edesc->bmAttributes)];
773 
774 	xfer->done = 1;
775 	if (!xfer->status && xfer->actlen < xfer->length &&
776 	    !(xfer->flags & USBD_SHORT_XFER_OK)) {
777 		DPRINTFN(-1,("%s: short transfer %d<%d\n", __func__,
778 		    xfer->actlen, xfer->length));
779 		xfer->status = USBD_SHORT_XFER;
780 	}
781 
782 	usb_tap(bus, xfer, USBTAP_DIR_IN);
783 
784 	/*
785 	 * We cannot dereference ``xfer'' after calling the callback as
786 	 * it might free it.
787 	 */
788 	status = xfer->status;
789 	flags = xfer->flags;
790 
791 	if (pipe->repeat) {
792 		if (xfer->callback)
793 			xfer->callback(xfer, xfer->priv, xfer->status);
794 		pipe->methods->done(xfer);
795 	} else {
796 		pipe->methods->done(xfer);
797 		if (xfer->callback)
798 			xfer->callback(xfer, xfer->priv, xfer->status);
799 	}
800 
801 	if ((flags & USBD_SYNCHRONOUS) && !polling)
802 		wakeup(xfer);
803 
804 	if (!pipe->repeat) {
805 		/* XXX should we stop the queue on all errors? */
806 		if ((status == USBD_CANCELLED || status == USBD_IOERROR ||
807 		     status == USBD_TIMEOUT) &&
808 		    pipe->iface != NULL)		/* not control pipe */
809 			pipe->running = 0;
810 		else
811 			usbd_start_next(pipe);
812 	}
813 }
814 
815 usbd_status
816 usb_insert_transfer(struct usbd_xfer *xfer)
817 {
818 	struct usbd_pipe *pipe = xfer->pipe;
819 	usbd_status err;
820 	int s;
821 
822 	DPRINTFN(5,("%s: pipe=%p running=%d timeout=%d\n", __func__,
823 	    pipe, pipe->running, xfer->timeout));
824 #ifdef DIAGNOSTIC
825 	if (xfer->busy_free != XFER_FREE) {
826 		printf("%s: xfer=%p not free\n", __func__, xfer);
827 		return (USBD_INVAL);
828 	}
829 	xfer->busy_free = XFER_ONQU;
830 #endif
831 	s = splusb();
832 	SIMPLEQ_INSERT_TAIL(&pipe->queue, xfer, next);
833 	if (pipe->running)
834 		err = USBD_IN_PROGRESS;
835 	else {
836 		pipe->running = 1;
837 		err = USBD_NORMAL_COMPLETION;
838 	}
839 	splx(s);
840 	return (err);
841 }
842 
843 /* Called at splusb() */
844 void
845 usbd_start_next(struct usbd_pipe *pipe)
846 {
847 	struct usbd_xfer *xfer;
848 	usbd_status err;
849 
850 	splsoftassert(IPL_SOFTUSB);
851 
852 #ifdef DIAGNOSTIC
853 	if (pipe == NULL) {
854 		printf("usbd_start_next: pipe == NULL\n");
855 		return;
856 	}
857 	if (pipe->methods == NULL || pipe->methods->start == NULL) {
858 		printf("%s: pipe=%p no start method\n", __func__, pipe);
859 		return;
860 	}
861 #endif
862 
863 	/* Get next request in queue. */
864 	xfer = SIMPLEQ_FIRST(&pipe->queue);
865 	DPRINTFN(5, ("%s: pipe=%p, xfer=%p\n", __func__, pipe, xfer));
866 	if (xfer == NULL) {
867 		pipe->running = 0;
868 	} else {
869 		err = pipe->methods->start(xfer);
870 		if (err != USBD_IN_PROGRESS) {
871 			printf("%s: error=%d\n", __func__, err);
872 			pipe->running = 0;
873 			/* XXX do what? */
874 		}
875 	}
876 }
877 
878 usbd_status
879 usbd_do_request(struct usbd_device *dev, usb_device_request_t *req, void *data)
880 {
881 	return (usbd_do_request_flags(dev, req, data, 0, 0,
882 	    USBD_DEFAULT_TIMEOUT));
883 }
884 
885 usbd_status
886 usbd_do_request_flags(struct usbd_device *dev, usb_device_request_t *req,
887     void *data, uint16_t flags, int *actlen, uint32_t timeout)
888 {
889 	struct usbd_xfer *xfer;
890 	usbd_status err;
891 
892 #ifdef DIAGNOSTIC
893 	if (dev->bus->intr_context) {
894 		printf("usbd_do_request: not in process context\n");
895 		return (USBD_INVAL);
896 	}
897 #endif
898 
899 	/* If the bus is gone, don't go any further. */
900 	if (usbd_is_dying(dev))
901 		return (USBD_IOERROR);
902 
903 	xfer = usbd_alloc_xfer(dev);
904 	if (xfer == NULL)
905 		return (USBD_NOMEM);
906 	usbd_setup_default_xfer(xfer, dev, 0, timeout, req, data,
907 	    UGETW(req->wLength), flags | USBD_SYNCHRONOUS, 0);
908 	err = usbd_transfer(xfer);
909 	if (actlen != NULL)
910 		*actlen = xfer->actlen;
911 	if (err == USBD_STALLED) {
912 		/*
913 		 * The control endpoint has stalled.  Control endpoints
914 		 * should not halt, but some may do so anyway so clear
915 		 * any halt condition.
916 		 */
917 		usb_device_request_t treq;
918 		usb_status_t status;
919 		u_int16_t s;
920 		usbd_status nerr;
921 
922 		treq.bmRequestType = UT_READ_ENDPOINT;
923 		treq.bRequest = UR_GET_STATUS;
924 		USETW(treq.wValue, 0);
925 		USETW(treq.wIndex, 0);
926 		USETW(treq.wLength, sizeof(usb_status_t));
927 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
928 		    &treq, &status, sizeof(usb_status_t), USBD_SYNCHRONOUS, 0);
929 		nerr = usbd_transfer(xfer);
930 		if (nerr)
931 			goto bad;
932 		s = UGETW(status.wStatus);
933 		DPRINTF(("%s: status = 0x%04x\n", __func__, s));
934 		if (!(s & UES_HALT))
935 			goto bad;
936 		treq.bmRequestType = UT_WRITE_ENDPOINT;
937 		treq.bRequest = UR_CLEAR_FEATURE;
938 		USETW(treq.wValue, UF_ENDPOINT_HALT);
939 		USETW(treq.wIndex, 0);
940 		USETW(treq.wLength, 0);
941 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
942 		    &treq, &status, 0, USBD_SYNCHRONOUS, 0);
943 		nerr = usbd_transfer(xfer);
944 		if (nerr)
945 			goto bad;
946 	}
947 
948  bad:
949 	usbd_free_xfer(xfer);
950 	return (err);
951 }
952 
953 void
954 usbd_request_async_cb(struct usbd_xfer *xfer, void *priv, usbd_status status)
955 {
956 	usbd_free_xfer(xfer);
957 }
958 
959 /*
960  * Execute a request without waiting for completion.
961  * Can be used from interrupt context.
962  */
963 usbd_status
964 usbd_request_async(struct usbd_xfer *xfer, usb_device_request_t *req,
965     void *priv, usbd_callback callback)
966 {
967 	usbd_status err;
968 
969 	if (callback == NULL)
970 		callback = usbd_request_async_cb;
971 
972 	usbd_setup_default_xfer(xfer, xfer->device, priv,
973 	    USBD_DEFAULT_TIMEOUT, req, NULL, UGETW(req->wLength),
974 	    USBD_NO_COPY, callback);
975 	err = usbd_transfer(xfer);
976 	if (err != USBD_IN_PROGRESS) {
977 		usbd_free_xfer(xfer);
978 		return (err);
979 	}
980 	return (USBD_NORMAL_COMPLETION);
981 }
982 
983 const struct usbd_quirks *
984 usbd_get_quirks(struct usbd_device *dev)
985 {
986 #ifdef DIAGNOSTIC
987 	if (dev == NULL) {
988 		printf("usbd_get_quirks: dev == NULL\n");
989 		return 0;
990 	}
991 #endif
992 	return (dev->quirks);
993 }
994 
995 /* XXX do periodic free() of free list */
996 
997 /*
998  * Called from keyboard driver when in polling mode.
999  */
1000 void
1001 usbd_dopoll(struct usbd_device *udev)
1002 {
1003 	udev->bus->methods->do_poll(udev->bus);
1004 }
1005 
1006 void
1007 usbd_set_polling(struct usbd_device *dev, int on)
1008 {
1009 	if (on)
1010 		dev->bus->use_polling++;
1011 	else
1012 		dev->bus->use_polling--;
1013 	/* When polling we need to make sure there is nothing pending to do. */
1014 	if (dev->bus->use_polling)
1015 		dev->bus->methods->soft_intr(dev->bus);
1016 }
1017 
1018 usb_endpoint_descriptor_t *
1019 usbd_get_endpoint_descriptor(struct usbd_interface *iface, u_int8_t address)
1020 {
1021 	struct usbd_endpoint *ep;
1022 	int i;
1023 
1024 	for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
1025 		ep = &iface->endpoints[i];
1026 		if (ep->edesc->bEndpointAddress == address)
1027 			return (iface->endpoints[i].edesc);
1028 	}
1029 	return (0);
1030 }
1031 
1032 /*
1033  * usbd_ratecheck() can limit the number of error messages that occurs.
1034  * When a device is unplugged it may take up to 0.25s for the hub driver
1035  * to notice it.  If the driver continuously tries to do I/O operations
1036  * this can generate a large number of messages.
1037  */
1038 int
1039 usbd_ratecheck(struct timeval *last)
1040 {
1041 	static struct timeval errinterval = { 0, 250000 }; /* 0.25 s*/
1042 
1043 	return (ratecheck(last, &errinterval));
1044 }
1045 
1046 /*
1047  * Search for a vendor/product pair in an array.  The item size is
1048  * given as an argument.
1049  */
1050 const struct usb_devno *
1051 usbd_match_device(const struct usb_devno *tbl, u_int nentries, u_int sz,
1052     u_int16_t vendor, u_int16_t product)
1053 {
1054 	while (nentries-- > 0) {
1055 		u_int16_t tproduct = tbl->ud_product;
1056 		if (tbl->ud_vendor == vendor &&
1057 		    (tproduct == product || tproduct == USB_PRODUCT_ANY))
1058 			return (tbl);
1059 		tbl = (const struct usb_devno *)((const char *)tbl + sz);
1060 	}
1061 	return (NULL);
1062 }
1063 
1064 void
1065 usbd_desc_iter_init(struct usbd_device *dev, struct usbd_desc_iter *iter)
1066 {
1067 	const usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
1068 
1069 	iter->cur = (const uByte *)cd;
1070 	iter->end = (const uByte *)cd + UGETW(cd->wTotalLength);
1071 }
1072 
1073 const usb_descriptor_t *
1074 usbd_desc_iter_next(struct usbd_desc_iter *iter)
1075 {
1076 	const usb_descriptor_t *desc;
1077 
1078 	if (iter->cur + sizeof(usb_descriptor_t) >= iter->end) {
1079 		if (iter->cur != iter->end)
1080 			printf("usbd_desc_iter_next: bad descriptor\n");
1081 		return NULL;
1082 	}
1083 	desc = (const usb_descriptor_t *)iter->cur;
1084 	if (desc->bLength == 0) {
1085 		printf("usbd_desc_iter_next: descriptor length = 0\n");
1086 		return NULL;
1087 	}
1088 	iter->cur += desc->bLength;
1089 	if (iter->cur > iter->end) {
1090 		printf("usbd_desc_iter_next: descriptor length too large\n");
1091 		return NULL;
1092 	}
1093 	return desc;
1094 }
1095 
1096 int
1097 usbd_str(usb_string_descriptor_t *p, int l, const char *s)
1098 {
1099 	int i;
1100 
1101 	if (l == 0)
1102 		return (0);
1103 	p->bLength = 2 * strlen(s) + 2;
1104 	if (l == 1)
1105 		return (1);
1106 	p->bDescriptorType = UDESC_STRING;
1107 	l -= 2;
1108 	for (i = 0; s[i] && l > 1; i++, l -= 2)
1109 		USETW2(p->bString[i], 0, s[i]);
1110 	return (2 * i + 2);
1111 }
1112