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