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