xref: /netbsd-src/sys/dev/usb/usbdi.c (revision cd22f25e6f6d1cc1f197fe8c5468a80f51d1c4e1)
1 /*	$NetBSD: usbdi.c,v 1.122 2008/04/28 20:24:01 martin Exp $	*/
2 /*	$FreeBSD: src/sys/dev/usb/usbdi.c,v 1.28 1999/11/17 22:33:49 n_hibma Exp $	*/
3 
4 /*
5  * Copyright (c) 1998 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: usbdi.c,v 1.122 2008/04/28 20:24:01 martin Exp $");
36 
37 #include "opt_compat_netbsd.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #if defined(__NetBSD__) || defined(__OpenBSD__)
42 #include <sys/kernel.h>
43 #include <sys/device.h>
44 #elif defined(__FreeBSD__)
45 #include <sys/module.h>
46 #include <sys/bus.h>
47 #include <sys/conf.h>
48 #include "usb_if.h"
49 #if defined(DIAGNOSTIC) && defined(__i386__)
50 #include <sys/cpu.h>
51 #endif
52 #endif
53 #include <sys/malloc.h>
54 #include <sys/proc.h>
55 
56 #include <sys/bus.h>
57 
58 #include <dev/usb/usb.h>
59 #include <dev/usb/usbdi.h>
60 #include <dev/usb/usbdi_util.h>
61 #include <dev/usb/usbdivar.h>
62 #include <dev/usb/usb_mem.h>
63 #include <dev/usb/usb_quirks.h>
64 
65 /* UTF-8 encoding stuff */
66 #include <fs/unicode.h>
67 
68 #ifdef USB_DEBUG
69 #define DPRINTF(x)	if (usbdebug) logprintf x
70 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
71 extern int usbdebug;
72 #else
73 #define DPRINTF(x)
74 #define DPRINTFN(n,x)
75 #endif
76 
77 Static usbd_status usbd_ar_pipe(usbd_pipe_handle pipe);
78 Static void usbd_do_request_async_cb
79 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
80 Static void usbd_start_next(usbd_pipe_handle pipe);
81 Static usbd_status usbd_open_pipe_ival
82 	(usbd_interface_handle, u_int8_t, u_int8_t, usbd_pipe_handle *, int);
83 
84 static inline int
85 usbd_xfer_isread(usbd_xfer_handle xfer)
86 {
87 	if (xfer->rqflags & URQ_REQUEST)
88 		return (xfer->request.bmRequestType & UT_READ);
89 	else
90 		return (xfer->pipe->endpoint->edesc->bEndpointAddress &
91 			UE_DIR_IN);
92 }
93 
94 #ifdef USB_DEBUG
95 void
96 usbd_dump_iface(struct usbd_interface *iface)
97 {
98 	printf("usbd_dump_iface: iface=%p\n", iface);
99 	if (iface == NULL)
100 		return;
101 	printf(" device=%p idesc=%p index=%d altindex=%d priv=%p\n",
102 	       iface->device, iface->idesc, iface->index, iface->altindex,
103 	       iface->priv);
104 }
105 
106 void
107 usbd_dump_device(struct usbd_device *dev)
108 {
109 	printf("usbd_dump_device: dev=%p\n", dev);
110 	if (dev == NULL)
111 		return;
112 	printf(" bus=%p default_pipe=%p\n", dev->bus, dev->default_pipe);
113 	printf(" address=%d config=%d depth=%d speed=%d self_powered=%d "
114 	       "power=%d langid=%d\n",
115 	       dev->address, dev->config, dev->depth, dev->speed,
116 	       dev->self_powered, dev->power, dev->langid);
117 }
118 
119 void
120 usbd_dump_endpoint(struct usbd_endpoint *endp)
121 {
122 	printf("usbd_dump_endpoint: endp=%p\n", endp);
123 	if (endp == NULL)
124 		return;
125 	printf(" edesc=%p refcnt=%d\n", endp->edesc, endp->refcnt);
126 	if (endp->edesc)
127 		printf(" bEndpointAddress=0x%02x\n",
128 		       endp->edesc->bEndpointAddress);
129 }
130 
131 void
132 usbd_dump_queue(usbd_pipe_handle pipe)
133 {
134 	usbd_xfer_handle xfer;
135 
136 	printf("usbd_dump_queue: pipe=%p\n", pipe);
137 	SIMPLEQ_FOREACH(xfer, &pipe->queue, next) {
138 		printf("  xfer=%p\n", xfer);
139 	}
140 }
141 
142 void
143 usbd_dump_pipe(usbd_pipe_handle pipe)
144 {
145 	printf("usbd_dump_pipe: pipe=%p\n", pipe);
146 	if (pipe == NULL)
147 		return;
148 	usbd_dump_iface(pipe->iface);
149 	usbd_dump_device(pipe->device);
150 	usbd_dump_endpoint(pipe->endpoint);
151 	printf(" (usbd_dump_pipe:)\n refcnt=%d running=%d aborting=%d\n",
152 	       pipe->refcnt, pipe->running, pipe->aborting);
153 	printf(" intrxfer=%p, repeat=%d, interval=%d\n",
154 	       pipe->intrxfer, pipe->repeat, pipe->interval);
155 }
156 #endif
157 
158 usbd_status
159 usbd_open_pipe(usbd_interface_handle iface, u_int8_t address,
160 	       u_int8_t flags, usbd_pipe_handle *pipe)
161 {
162 	return (usbd_open_pipe_ival(iface, address, flags, pipe,
163 				    USBD_DEFAULT_INTERVAL));
164 }
165 
166 usbd_status
167 usbd_open_pipe_ival(usbd_interface_handle iface, u_int8_t address,
168 		    u_int8_t flags, usbd_pipe_handle *pipe, int ival)
169 {
170 	usbd_pipe_handle p;
171 	struct usbd_endpoint *ep;
172 	usbd_status err;
173 	int i;
174 
175 	DPRINTFN(3,("usbd_open_pipe: iface=%p address=0x%x flags=0x%x\n",
176 		    iface, address, flags));
177 
178 	for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
179 		ep = &iface->endpoints[i];
180 		if (ep->edesc == NULL)
181 			return (USBD_IOERROR);
182 		if (ep->edesc->bEndpointAddress == address)
183 			goto found;
184 	}
185 	return (USBD_BAD_ADDRESS);
186  found:
187 	if ((flags & USBD_EXCLUSIVE_USE) && ep->refcnt != 0)
188 		return (USBD_IN_USE);
189 	err = usbd_setup_pipe(iface->device, iface, ep, ival, &p);
190 	if (err)
191 		return (err);
192 	LIST_INSERT_HEAD(&iface->pipes, p, next);
193 	*pipe = p;
194 	return (USBD_NORMAL_COMPLETION);
195 }
196 
197 usbd_status
198 usbd_open_pipe_intr(usbd_interface_handle iface, u_int8_t address,
199 		    u_int8_t flags, usbd_pipe_handle *pipe,
200 		    usbd_private_handle priv, void *buffer, u_int32_t len,
201 		    usbd_callback cb, int ival)
202 {
203 	usbd_status err;
204 	usbd_xfer_handle xfer;
205 	usbd_pipe_handle ipipe;
206 
207 	DPRINTFN(3,("usbd_open_pipe_intr: address=0x%x flags=0x%x len=%d\n",
208 		    address, flags, len));
209 
210 	err = usbd_open_pipe_ival(iface, address, USBD_EXCLUSIVE_USE,
211 				  &ipipe, ival);
212 	if (err)
213 		return (err);
214 	xfer = usbd_alloc_xfer(iface->device);
215 	if (xfer == NULL) {
216 		err = USBD_NOMEM;
217 		goto bad1;
218 	}
219 	usbd_setup_xfer(xfer, ipipe, priv, buffer, len, flags,
220 	    USBD_NO_TIMEOUT, cb);
221 	ipipe->intrxfer = xfer;
222 	ipipe->repeat = 1;
223 	err = usbd_transfer(xfer);
224 	*pipe = ipipe;
225 	if (err != USBD_IN_PROGRESS)
226 		goto bad2;
227 	return (USBD_NORMAL_COMPLETION);
228 
229  bad2:
230 	ipipe->intrxfer = NULL;
231 	ipipe->repeat = 0;
232 	usbd_free_xfer(xfer);
233  bad1:
234 	usbd_close_pipe(ipipe);
235 	return (err);
236 }
237 
238 usbd_status
239 usbd_close_pipe(usbd_pipe_handle pipe)
240 {
241 #ifdef DIAGNOSTIC
242 	if (pipe == NULL) {
243 		printf("usbd_close_pipe: pipe==NULL\n");
244 		return (USBD_NORMAL_COMPLETION);
245 	}
246 #endif
247 
248 	if (--pipe->refcnt != 0)
249 		return (USBD_NORMAL_COMPLETION);
250 	if (! SIMPLEQ_EMPTY(&pipe->queue))
251 		return (USBD_PENDING_REQUESTS);
252 	LIST_REMOVE(pipe, next);
253 	pipe->endpoint->refcnt--;
254 	pipe->methods->close(pipe);
255 	if (pipe->intrxfer != NULL)
256 		usbd_free_xfer(pipe->intrxfer);
257 	free(pipe, M_USB);
258 	return (USBD_NORMAL_COMPLETION);
259 }
260 
261 usbd_status
262 usbd_transfer(usbd_xfer_handle xfer)
263 {
264 	usbd_pipe_handle pipe = xfer->pipe;
265 	usb_dma_t *dmap = &xfer->dmabuf;
266 	usbd_status err;
267 	unsigned int size, flags;
268 	int s;
269 
270 	DPRINTFN(5,("usbd_transfer: xfer=%p, flags=%#x, pipe=%p, running=%d\n",
271 		    xfer, xfer->flags, pipe, pipe->running));
272 #ifdef USB_DEBUG
273 	if (usbdebug > 5)
274 		usbd_dump_queue(pipe);
275 #endif
276 	xfer->done = 0;
277 
278 	if (pipe->aborting)
279 		return (USBD_CANCELLED);
280 
281 	size = xfer->length;
282 	/* If there is no buffer, allocate one. */
283 	if (!(xfer->rqflags & URQ_DEV_DMABUF) && size != 0) {
284 		struct usbd_bus *bus = pipe->device->bus;
285 
286 #ifdef DIAGNOSTIC
287 		if (xfer->rqflags & URQ_AUTO_DMABUF)
288 			printf("usbd_transfer: has old buffer!\n");
289 #endif
290 		err = bus->methods->allocm(bus, dmap, size);
291 		if (err)
292 			return (err);
293 		xfer->rqflags |= URQ_AUTO_DMABUF;
294 	}
295 
296 	flags = xfer->flags;
297 
298 	/* Copy data if going out. */
299 	if (!(flags & USBD_NO_COPY) && size != 0 && !usbd_xfer_isread(xfer))
300 		memcpy(KERNADDR(dmap, 0), xfer->buffer, size);
301 
302 	/* xfer is not valid after the transfer method unless synchronous */
303 	err = pipe->methods->transfer(xfer);
304 
305 	if (err != USBD_IN_PROGRESS && err) {
306 		/* The transfer has not been queued, so free buffer. */
307 		if (xfer->rqflags & URQ_AUTO_DMABUF) {
308 			struct usbd_bus *bus = pipe->device->bus;
309 
310 			bus->methods->freem(bus, &xfer->dmabuf);
311 			xfer->rqflags &= ~URQ_AUTO_DMABUF;
312 		}
313 	}
314 
315 	if (!(flags & USBD_SYNCHRONOUS))
316 		return (err);
317 
318 	/* Sync transfer, wait for completion. */
319 	if (err != USBD_IN_PROGRESS)
320 		return (err);
321 	s = splusb();
322 	if (!xfer->done) {
323 		if (pipe->device->bus->use_polling)
324 			panic("usbd_transfer: not done");
325 		tsleep(xfer, PRIBIO, "usbsyn", 0);
326 	}
327 	splx(s);
328 	return (xfer->status);
329 }
330 
331 /* Like usbd_transfer(), but waits for completion. */
332 usbd_status
333 usbd_sync_transfer(usbd_xfer_handle xfer)
334 {
335 	xfer->flags |= USBD_SYNCHRONOUS;
336 	return (usbd_transfer(xfer));
337 }
338 
339 void *
340 usbd_alloc_buffer(usbd_xfer_handle xfer, u_int32_t size)
341 {
342 	struct usbd_bus *bus = xfer->device->bus;
343 	usbd_status err;
344 
345 #ifdef DIAGNOSTIC
346 	if (xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))
347 		printf("usbd_alloc_buffer: xfer already has a buffer\n");
348 #endif
349 	err = bus->methods->allocm(bus, &xfer->dmabuf, size);
350 	if (err)
351 		return (NULL);
352 	xfer->rqflags |= URQ_DEV_DMABUF;
353 	return (KERNADDR(&xfer->dmabuf, 0));
354 }
355 
356 void
357 usbd_free_buffer(usbd_xfer_handle xfer)
358 {
359 #ifdef DIAGNOSTIC
360 	if (!(xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))) {
361 		printf("usbd_free_buffer: no buffer\n");
362 		return;
363 	}
364 #endif
365 	xfer->rqflags &= ~(URQ_DEV_DMABUF | URQ_AUTO_DMABUF);
366 	xfer->device->bus->methods->freem(xfer->device->bus, &xfer->dmabuf);
367 }
368 
369 void *
370 usbd_get_buffer(usbd_xfer_handle xfer)
371 {
372 	if (!(xfer->rqflags & URQ_DEV_DMABUF))
373 		return (0);
374 	return (KERNADDR(&xfer->dmabuf, 0));
375 }
376 
377 usbd_xfer_handle
378 usbd_alloc_xfer(usbd_device_handle dev)
379 {
380 	usbd_xfer_handle xfer;
381 
382 	xfer = dev->bus->methods->allocx(dev->bus);
383 	if (xfer == NULL)
384 		return (NULL);
385 	xfer->device = dev;
386 	usb_callout_init(xfer->timeout_handle);
387 	DPRINTFN(5,("usbd_alloc_xfer() = %p\n", xfer));
388 	return (xfer);
389 }
390 
391 usbd_status
392 usbd_free_xfer(usbd_xfer_handle xfer)
393 {
394 	DPRINTFN(5,("usbd_free_xfer: %p\n", xfer));
395 	if (xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))
396 		usbd_free_buffer(xfer);
397 #if defined(__NetBSD__) && defined(DIAGNOSTIC)
398 	if (callout_pending(&xfer->timeout_handle)) {
399 		callout_stop(&xfer->timeout_handle);
400 		printf("usbd_free_xfer: timout_handle pending");
401 	}
402 #endif
403 	xfer->device->bus->methods->freex(xfer->device->bus, xfer);
404 	return (USBD_NORMAL_COMPLETION);
405 }
406 
407 void
408 usbd_setup_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
409 		usbd_private_handle priv, void *buffer, u_int32_t length,
410 		u_int16_t flags, u_int32_t timeout,
411 		usbd_callback callback)
412 {
413 	xfer->pipe = pipe;
414 	xfer->priv = priv;
415 	xfer->buffer = buffer;
416 	xfer->length = length;
417 	xfer->actlen = 0;
418 	xfer->flags = flags;
419 	xfer->timeout = timeout;
420 	xfer->status = USBD_NOT_STARTED;
421 	xfer->callback = callback;
422 	xfer->rqflags &= ~URQ_REQUEST;
423 	xfer->nframes = 0;
424 }
425 
426 void
427 usbd_setup_default_xfer(usbd_xfer_handle xfer, usbd_device_handle dev,
428 			usbd_private_handle priv, u_int32_t timeout,
429 			usb_device_request_t *req, void *buffer,
430 			u_int32_t length, u_int16_t flags,
431 			usbd_callback callback)
432 {
433 	xfer->pipe = dev->default_pipe;
434 	xfer->priv = priv;
435 	xfer->buffer = buffer;
436 	xfer->length = length;
437 	xfer->actlen = 0;
438 	xfer->flags = flags;
439 	xfer->timeout = timeout;
440 	xfer->status = USBD_NOT_STARTED;
441 	xfer->callback = callback;
442 	xfer->request = *req;
443 	xfer->rqflags |= URQ_REQUEST;
444 	xfer->nframes = 0;
445 }
446 
447 void
448 usbd_setup_isoc_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
449 		     usbd_private_handle priv, u_int16_t *frlengths,
450 		     u_int32_t nframes, u_int16_t flags, usbd_callback callback)
451 {
452 	xfer->pipe = pipe;
453 	xfer->priv = priv;
454 	xfer->buffer = 0;
455 	xfer->length = 0;
456 	xfer->actlen = 0;
457 	xfer->flags = flags;
458 	xfer->timeout = USBD_NO_TIMEOUT;
459 	xfer->status = USBD_NOT_STARTED;
460 	xfer->callback = callback;
461 	xfer->rqflags &= ~URQ_REQUEST;
462 	xfer->frlengths = frlengths;
463 	xfer->nframes = nframes;
464 }
465 
466 void
467 usbd_get_xfer_status(usbd_xfer_handle xfer, usbd_private_handle *priv,
468 		     void **buffer, u_int32_t *count, usbd_status *status)
469 {
470 	if (priv != NULL)
471 		*priv = xfer->priv;
472 	if (buffer != NULL)
473 		*buffer = xfer->buffer;
474 	if (count != NULL)
475 		*count = xfer->actlen;
476 	if (status != NULL)
477 		*status = xfer->status;
478 }
479 
480 usb_config_descriptor_t *
481 usbd_get_config_descriptor(usbd_device_handle dev)
482 {
483 #ifdef DIAGNOSTIC
484 	if (dev == NULL) {
485 		printf("usbd_get_config_descriptor: dev == NULL\n");
486 		return (NULL);
487 	}
488 #endif
489 	return (dev->cdesc);
490 }
491 
492 usb_interface_descriptor_t *
493 usbd_get_interface_descriptor(usbd_interface_handle iface)
494 {
495 #ifdef DIAGNOSTIC
496 	if (iface == NULL) {
497 		printf("usbd_get_interface_descriptor: dev == NULL\n");
498 		return (NULL);
499 	}
500 #endif
501 	return (iface->idesc);
502 }
503 
504 usb_device_descriptor_t *
505 usbd_get_device_descriptor(usbd_device_handle dev)
506 {
507 	return (&dev->ddesc);
508 }
509 
510 usb_endpoint_descriptor_t *
511 usbd_interface2endpoint_descriptor(usbd_interface_handle iface, u_int8_t index)
512 {
513 	if (index >= iface->idesc->bNumEndpoints)
514 		return (0);
515 	return (iface->endpoints[index].edesc);
516 }
517 
518 usbd_status
519 usbd_abort_pipe(usbd_pipe_handle pipe)
520 {
521 	usbd_status err;
522 	int s;
523 
524 #ifdef DIAGNOSTIC
525 	if (pipe == NULL) {
526 		printf("usbd_close_pipe: pipe==NULL\n");
527 		return (USBD_NORMAL_COMPLETION);
528 	}
529 #endif
530 	s = splusb();
531 	err = usbd_ar_pipe(pipe);
532 	splx(s);
533 	return (err);
534 }
535 
536 usbd_status
537 usbd_clear_endpoint_stall(usbd_pipe_handle pipe)
538 {
539 	usbd_device_handle dev = pipe->device;
540 	usb_device_request_t req;
541 	usbd_status err;
542 
543 	DPRINTFN(8, ("usbd_clear_endpoint_stall\n"));
544 
545 	/*
546 	 * Clearing en endpoint stall resets the endpoint toggle, so
547 	 * do the same to the HC toggle.
548 	 */
549 	pipe->methods->cleartoggle(pipe);
550 
551 	req.bmRequestType = UT_WRITE_ENDPOINT;
552 	req.bRequest = UR_CLEAR_FEATURE;
553 	USETW(req.wValue, UF_ENDPOINT_HALT);
554 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
555 	USETW(req.wLength, 0);
556 	err = usbd_do_request(dev, &req, 0);
557 #if 0
558 XXX should we do this?
559 	if (!err) {
560 		pipe->state = USBD_PIPE_ACTIVE;
561 		/* XXX activate pipe */
562 	}
563 #endif
564 	return (err);
565 }
566 
567 usbd_status
568 usbd_clear_endpoint_stall_async(usbd_pipe_handle pipe)
569 {
570 	usbd_device_handle dev = pipe->device;
571 	usb_device_request_t req;
572 	usbd_status err;
573 
574 	pipe->methods->cleartoggle(pipe);
575 
576 	req.bmRequestType = UT_WRITE_ENDPOINT;
577 	req.bRequest = UR_CLEAR_FEATURE;
578 	USETW(req.wValue, UF_ENDPOINT_HALT);
579 	USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
580 	USETW(req.wLength, 0);
581 	err = usbd_do_request_async(dev, &req, 0);
582 	return (err);
583 }
584 
585 void
586 usbd_clear_endpoint_toggle(usbd_pipe_handle pipe)
587 {
588 	pipe->methods->cleartoggle(pipe);
589 }
590 
591 usbd_status
592 usbd_endpoint_count(usbd_interface_handle iface, u_int8_t *count)
593 {
594 #ifdef DIAGNOSTIC
595 	if (iface == NULL || iface->idesc == NULL) {
596 		printf("usbd_endpoint_count: NULL pointer\n");
597 		return (USBD_INVAL);
598 	}
599 #endif
600 	*count = iface->idesc->bNumEndpoints;
601 	return (USBD_NORMAL_COMPLETION);
602 }
603 
604 usbd_status
605 usbd_interface_count(usbd_device_handle dev, u_int8_t *count)
606 {
607 	if (dev->cdesc == NULL)
608 		return (USBD_NOT_CONFIGURED);
609 	*count = dev->cdesc->bNumInterface;
610 	return (USBD_NORMAL_COMPLETION);
611 }
612 
613 void
614 usbd_interface2device_handle(usbd_interface_handle iface,
615 			     usbd_device_handle *dev)
616 {
617 	*dev = iface->device;
618 }
619 
620 usbd_status
621 usbd_device2interface_handle(usbd_device_handle dev,
622 			     u_int8_t ifaceno, usbd_interface_handle *iface)
623 {
624 	if (dev->cdesc == NULL)
625 		return (USBD_NOT_CONFIGURED);
626 	if (ifaceno >= dev->cdesc->bNumInterface)
627 		return (USBD_INVAL);
628 	*iface = &dev->ifaces[ifaceno];
629 	return (USBD_NORMAL_COMPLETION);
630 }
631 
632 usbd_device_handle
633 usbd_pipe2device_handle(usbd_pipe_handle pipe)
634 {
635 	return (pipe->device);
636 }
637 
638 /* XXXX use altno */
639 usbd_status
640 usbd_set_interface(usbd_interface_handle iface, int altidx)
641 {
642 	usb_device_request_t req;
643 	usbd_status err;
644 	void *endpoints;
645 
646 	if (LIST_FIRST(&iface->pipes) != 0)
647 		return (USBD_IN_USE);
648 
649 	endpoints = iface->endpoints;
650 	err = usbd_fill_iface_data(iface->device, iface->index, altidx);
651 	if (err)
652 		return (err);
653 
654 	/* new setting works, we can free old endpoints */
655 	if (endpoints != NULL)
656 		free(endpoints, M_USB);
657 
658 #ifdef DIAGNOSTIC
659 	if (iface->idesc == NULL) {
660 		printf("usbd_set_interface: NULL pointer\n");
661 		return (USBD_INVAL);
662 	}
663 #endif
664 
665 	req.bmRequestType = UT_WRITE_INTERFACE;
666 	req.bRequest = UR_SET_INTERFACE;
667 	USETW(req.wValue, iface->idesc->bAlternateSetting);
668 	USETW(req.wIndex, iface->idesc->bInterfaceNumber);
669 	USETW(req.wLength, 0);
670 	return (usbd_do_request(iface->device, &req, 0));
671 }
672 
673 int
674 usbd_get_no_alts(usb_config_descriptor_t *cdesc, int ifaceno)
675 {
676 	char *p = (char *)cdesc;
677 	char *end = p + UGETW(cdesc->wTotalLength);
678 	usb_interface_descriptor_t *d;
679 	int n;
680 
681 	for (n = 0; p < end; p += d->bLength) {
682 		d = (usb_interface_descriptor_t *)p;
683 		if (p + d->bLength <= end &&
684 		    d->bDescriptorType == UDESC_INTERFACE &&
685 		    d->bInterfaceNumber == ifaceno)
686 			n++;
687 	}
688 	return (n);
689 }
690 
691 int
692 usbd_get_interface_altindex(usbd_interface_handle iface)
693 {
694 	return (iface->altindex);
695 }
696 
697 usbd_status
698 usbd_get_interface(usbd_interface_handle iface, u_int8_t *aiface)
699 {
700 	usb_device_request_t req;
701 
702 	req.bmRequestType = UT_READ_INTERFACE;
703 	req.bRequest = UR_GET_INTERFACE;
704 	USETW(req.wValue, 0);
705 	USETW(req.wIndex, iface->idesc->bInterfaceNumber);
706 	USETW(req.wLength, 1);
707 	return (usbd_do_request(iface->device, &req, aiface));
708 }
709 
710 /*** Internal routines ***/
711 
712 /* Dequeue all pipe operations, called at splusb(). */
713 Static usbd_status
714 usbd_ar_pipe(usbd_pipe_handle pipe)
715 {
716 	usbd_xfer_handle xfer;
717 
718 	SPLUSBCHECK;
719 
720 	DPRINTFN(2,("usbd_ar_pipe: pipe=%p\n", pipe));
721 #ifdef USB_DEBUG
722 	if (usbdebug > 5)
723 		usbd_dump_queue(pipe);
724 #endif
725 	pipe->repeat = 0;
726 	pipe->aborting = 1;
727 	while ((xfer = SIMPLEQ_FIRST(&pipe->queue)) != NULL) {
728 		DPRINTFN(2,("usbd_ar_pipe: pipe=%p xfer=%p (methods=%p)\n",
729 			    pipe, xfer, pipe->methods));
730 		/* Make the HC abort it (and invoke the callback). */
731 		pipe->methods->abort(xfer);
732 		/* XXX only for non-0 usbd_clear_endpoint_stall(pipe); */
733 	}
734 	pipe->aborting = 0;
735 	return (USBD_NORMAL_COMPLETION);
736 }
737 
738 /* Called at splusb() */
739 void
740 usb_transfer_complete(usbd_xfer_handle xfer)
741 {
742 	usbd_pipe_handle pipe = xfer->pipe;
743 	usb_dma_t *dmap = &xfer->dmabuf;
744 	int sync = xfer->flags & USBD_SYNCHRONOUS;
745 	int erred = xfer->status == USBD_CANCELLED ||
746 	    xfer->status == USBD_TIMEOUT;
747 	int repeat, polling;
748 
749 	SPLUSBCHECK;
750 
751 	DPRINTFN(5, ("usb_transfer_complete: pipe=%p xfer=%p status=%d "
752 		     "actlen=%d\n", pipe, xfer, xfer->status, xfer->actlen));
753 #ifdef DIAGNOSTIC
754 	if (xfer->busy_free != XFER_ONQU) {
755 		printf("usb_transfer_complete: xfer=%p not busy 0x%08x\n",
756 		       xfer, xfer->busy_free);
757 	}
758 #endif
759 
760 #ifdef DIAGNOSTIC
761 	if (pipe == NULL) {
762 		printf("usbd_transfer_cb: pipe==0, xfer=%p\n", xfer);
763 		return;
764 	}
765 #endif
766 	repeat = pipe->repeat;
767 	polling = pipe->device->bus->use_polling;
768 	/* XXXX */
769 	if (polling)
770 		pipe->running = 0;
771 
772 	if (!(xfer->flags & USBD_NO_COPY) && xfer->actlen != 0 &&
773 	    usbd_xfer_isread(xfer)) {
774 #ifdef DIAGNOSTIC
775 		if (xfer->actlen > xfer->length) {
776 			printf("usb_transfer_complete: actlen > len %d > %d\n",
777 			       xfer->actlen, xfer->length);
778 			xfer->actlen = xfer->length;
779 		}
780 #endif
781 		memcpy(xfer->buffer, KERNADDR(dmap, 0), xfer->actlen);
782 	}
783 
784 	/* if we allocated the buffer in usbd_transfer() we free it here. */
785 	if (xfer->rqflags & URQ_AUTO_DMABUF) {
786 		if (!repeat) {
787 			struct usbd_bus *bus = pipe->device->bus;
788 			bus->methods->freem(bus, dmap);
789 			xfer->rqflags &= ~URQ_AUTO_DMABUF;
790 		}
791 	}
792 
793 	if (!repeat) {
794 		/* Remove request from queue. */
795 #ifdef DIAGNOSTIC
796 		if (xfer != SIMPLEQ_FIRST(&pipe->queue))
797 			printf("usb_transfer_complete: bad dequeue %p != %p\n",
798 			       xfer, SIMPLEQ_FIRST(&pipe->queue));
799 		xfer->busy_free = XFER_BUSY;
800 #endif
801 		SIMPLEQ_REMOVE_HEAD(&pipe->queue, next);
802 	}
803 	DPRINTFN(5,("usb_transfer_complete: repeat=%d new head=%p\n",
804 		    repeat, SIMPLEQ_FIRST(&pipe->queue)));
805 
806 	/* Count completed transfers. */
807 	++pipe->device->bus->stats.uds_requests
808 		[pipe->endpoint->edesc->bmAttributes & UE_XFERTYPE];
809 
810 	xfer->done = 1;
811 	if (!xfer->status && xfer->actlen < xfer->length &&
812 	    !(xfer->flags & USBD_SHORT_XFER_OK)) {
813 		DPRINTFN(-1,("usbd_transfer_cb: short transfer %d<%d\n",
814 			     xfer->actlen, xfer->length));
815 		xfer->status = USBD_SHORT_XFER;
816 	}
817 
818 	if (xfer->callback)
819 		xfer->callback(xfer, xfer->priv, xfer->status);
820 
821 #ifdef DIAGNOSTIC
822 	if (pipe->methods->done != NULL)
823 		pipe->methods->done(xfer);
824 	else
825 		printf("usb_transfer_complete: pipe->methods->done == NULL\n");
826 #else
827 	pipe->methods->done(xfer);
828 #endif
829 
830 	if (sync && !polling)
831 		wakeup(xfer);
832 
833 	if (!repeat) {
834 		/* XXX should we stop the queue on all errors? */
835 		if (erred && pipe->iface != NULL)	/* not control pipe */
836 			pipe->running = 0;
837 		else
838 			usbd_start_next(pipe);
839 	}
840 }
841 
842 usbd_status
843 usb_insert_transfer(usbd_xfer_handle xfer)
844 {
845 	usbd_pipe_handle pipe = xfer->pipe;
846 	usbd_status err;
847 	int s;
848 
849 	DPRINTFN(5,("usb_insert_transfer: pipe=%p running=%d timeout=%d\n",
850 		    pipe, pipe->running, xfer->timeout));
851 #ifdef DIAGNOSTIC
852 	if (xfer->busy_free != XFER_BUSY) {
853 		printf("usb_insert_transfer: xfer=%p not busy 0x%08x\n",
854 		       xfer, xfer->busy_free);
855 		return (USBD_INVAL);
856 	}
857 	xfer->busy_free = XFER_ONQU;
858 #endif
859 	s = splusb();
860 	SIMPLEQ_INSERT_TAIL(&pipe->queue, xfer, next);
861 	if (pipe->running)
862 		err = USBD_IN_PROGRESS;
863 	else {
864 		pipe->running = 1;
865 		err = USBD_NORMAL_COMPLETION;
866 	}
867 	splx(s);
868 	return (err);
869 }
870 
871 /* Called at splusb() */
872 void
873 usbd_start_next(usbd_pipe_handle pipe)
874 {
875 	usbd_xfer_handle xfer;
876 	usbd_status err;
877 
878 	SPLUSBCHECK;
879 
880 #ifdef DIAGNOSTIC
881 	if (pipe == NULL) {
882 		printf("usbd_start_next: pipe == NULL\n");
883 		return;
884 	}
885 	if (pipe->methods == NULL || pipe->methods->start == NULL) {
886 		printf("usbd_start_next: pipe=%p no start method\n", pipe);
887 		return;
888 	}
889 #endif
890 
891 	/* Get next request in queue. */
892 	xfer = SIMPLEQ_FIRST(&pipe->queue);
893 	DPRINTFN(5, ("usbd_start_next: pipe=%p, xfer=%p\n", pipe, xfer));
894 	if (xfer == NULL) {
895 		pipe->running = 0;
896 	} else {
897 		err = pipe->methods->start(xfer);
898 		if (err != USBD_IN_PROGRESS) {
899 			printf("usbd_start_next: error=%d\n", err);
900 			pipe->running = 0;
901 			/* XXX do what? */
902 		}
903 	}
904 }
905 
906 usbd_status
907 usbd_do_request(usbd_device_handle dev, usb_device_request_t *req, void *data)
908 {
909 	return (usbd_do_request_flags(dev, req, data, 0, 0,
910 				      USBD_DEFAULT_TIMEOUT));
911 }
912 
913 usbd_status
914 usbd_do_request_flags(usbd_device_handle dev, usb_device_request_t *req,
915 		      void *data, u_int16_t flags, int *actlen, u_int32_t timo)
916 {
917 	return (usbd_do_request_flags_pipe(dev, dev->default_pipe, req,
918 					   data, flags, actlen, timo));
919 }
920 
921 usbd_status
922 usbd_do_request_flags_pipe(usbd_device_handle dev, usbd_pipe_handle pipe,
923 	usb_device_request_t *req, void *data, u_int16_t flags, int *actlen,
924 	u_int32_t timeout)
925 {
926 	usbd_xfer_handle xfer;
927 	usbd_status err;
928 
929 #ifdef DIAGNOSTIC
930 #if defined(__i386__) && defined(__FreeBSD__)
931 	KASSERT(intr_nesting_level == 0,
932 	       	("usbd_do_request: in interrupt context"));
933 #endif
934 	if (dev->bus->intr_context) {
935 		printf("usbd_do_request: not in process context\n");
936 		return (USBD_INVAL);
937 	}
938 #endif
939 
940 	xfer = usbd_alloc_xfer(dev);
941 	if (xfer == NULL)
942 		return (USBD_NOMEM);
943 	usbd_setup_default_xfer(xfer, dev, 0, timeout, req,
944 				data, UGETW(req->wLength), flags, 0);
945 	xfer->pipe = pipe;
946 	err = usbd_sync_transfer(xfer);
947 #if defined(USB_DEBUG) || defined(DIAGNOSTIC)
948 	if (xfer->actlen > xfer->length) {
949 		DPRINTF(("usbd_do_request: overrun addr=%d type=0x%02x req=0x"
950 			 "%02x val=%d index=%d rlen=%d length=%d actlen=%d\n",
951 			 dev->address, xfer->request.bmRequestType,
952 			 xfer->request.bRequest, UGETW(xfer->request.wValue),
953 			 UGETW(xfer->request.wIndex),
954 			 UGETW(xfer->request.wLength),
955 			 xfer->length, xfer->actlen));
956 	}
957 #endif
958 	if (actlen != NULL)
959 		*actlen = xfer->actlen;
960 	if (err == USBD_STALLED) {
961 		/*
962 		 * The control endpoint has stalled.  Control endpoints
963 		 * should not halt, but some may do so anyway so clear
964 		 * any halt condition.
965 		 */
966 		usb_device_request_t treq;
967 		usb_status_t status;
968 		u_int16_t s;
969 		usbd_status nerr;
970 
971 		treq.bmRequestType = UT_READ_ENDPOINT;
972 		treq.bRequest = UR_GET_STATUS;
973 		USETW(treq.wValue, 0);
974 		USETW(treq.wIndex, 0);
975 		USETW(treq.wLength, sizeof(usb_status_t));
976 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
977 					   &treq, &status,sizeof(usb_status_t),
978 					   0, 0);
979 		nerr = usbd_sync_transfer(xfer);
980 		if (nerr)
981 			goto bad;
982 		s = UGETW(status.wStatus);
983 		DPRINTF(("usbd_do_request: status = 0x%04x\n", s));
984 		if (!(s & UES_HALT))
985 			goto bad;
986 		treq.bmRequestType = UT_WRITE_ENDPOINT;
987 		treq.bRequest = UR_CLEAR_FEATURE;
988 		USETW(treq.wValue, UF_ENDPOINT_HALT);
989 		USETW(treq.wIndex, 0);
990 		USETW(treq.wLength, 0);
991 		usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT,
992 					   &treq, &status, 0, 0, 0);
993 		nerr = usbd_sync_transfer(xfer);
994 		if (nerr)
995 			goto bad;
996 	}
997 
998  bad:
999 	usbd_free_xfer(xfer);
1000 	return (err);
1001 }
1002 
1003 void
1004 usbd_do_request_async_cb(usbd_xfer_handle xfer,
1005     usbd_private_handle priv, usbd_status status)
1006 {
1007 #if defined(USB_DEBUG) || defined(DIAGNOSTIC)
1008 	if (xfer->actlen > xfer->length) {
1009 		DPRINTF(("usbd_do_request: overrun addr=%d type=0x%02x req=0x"
1010 			 "%02x val=%d index=%d rlen=%d length=%d actlen=%d\n",
1011 			 xfer->pipe->device->address,
1012 			 xfer->request.bmRequestType,
1013 			 xfer->request.bRequest, UGETW(xfer->request.wValue),
1014 			 UGETW(xfer->request.wIndex),
1015 			 UGETW(xfer->request.wLength),
1016 			 xfer->length, xfer->actlen));
1017 	}
1018 #endif
1019 	usbd_free_xfer(xfer);
1020 }
1021 
1022 /*
1023  * Execute a request without waiting for completion.
1024  * Can be used from interrupt context.
1025  */
1026 usbd_status
1027 usbd_do_request_async(usbd_device_handle dev, usb_device_request_t *req,
1028 		      void *data)
1029 {
1030 	usbd_xfer_handle xfer;
1031 	usbd_status err;
1032 
1033 	xfer = usbd_alloc_xfer(dev);
1034 	if (xfer == NULL)
1035 		return (USBD_NOMEM);
1036 	usbd_setup_default_xfer(xfer, dev, 0, USBD_DEFAULT_TIMEOUT, req,
1037 	    data, UGETW(req->wLength), 0, usbd_do_request_async_cb);
1038 	err = usbd_transfer(xfer);
1039 	if (err != USBD_IN_PROGRESS) {
1040 		usbd_free_xfer(xfer);
1041 		return (err);
1042 	}
1043 	return (USBD_NORMAL_COMPLETION);
1044 }
1045 
1046 const struct usbd_quirks *
1047 usbd_get_quirks(usbd_device_handle dev)
1048 {
1049 #ifdef DIAGNOSTIC
1050 	if (dev == NULL) {
1051 		printf("usbd_get_quirks: dev == NULL\n");
1052 		return 0;
1053 	}
1054 #endif
1055 	return (dev->quirks);
1056 }
1057 
1058 /* XXX do periodic free() of free list */
1059 
1060 /*
1061  * Called from keyboard driver when in polling mode.
1062  */
1063 void
1064 usbd_dopoll(usbd_interface_handle iface)
1065 {
1066 	iface->device->bus->methods->do_poll(iface->device->bus);
1067 }
1068 
1069 void
1070 usbd_set_polling(usbd_device_handle dev, int on)
1071 {
1072 	if (on)
1073 		dev->bus->use_polling++;
1074 	else
1075 		dev->bus->use_polling--;
1076 	/* When polling we need to make sure there is nothing pending to do. */
1077 	if (dev->bus->use_polling)
1078 		dev->bus->methods->soft_intr(dev->bus);
1079 }
1080 
1081 
1082 usb_endpoint_descriptor_t *
1083 usbd_get_endpoint_descriptor(usbd_interface_handle iface, u_int8_t address)
1084 {
1085 	struct usbd_endpoint *ep;
1086 	int i;
1087 
1088 	for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
1089 		ep = &iface->endpoints[i];
1090 		if (ep->edesc->bEndpointAddress == address)
1091 			return (iface->endpoints[i].edesc);
1092 	}
1093 	return (0);
1094 }
1095 
1096 /*
1097  * usbd_ratecheck() can limit the number of error messages that occurs.
1098  * When a device is unplugged it may take up to 0.25s for the hub driver
1099  * to notice it.  If the driver continuosly tries to do I/O operations
1100  * this can generate a large number of messages.
1101  */
1102 int
1103 usbd_ratecheck(struct timeval *last)
1104 {
1105 	static struct timeval errinterval = { 0, 250000 }; /* 0.25 s*/
1106 
1107 	return (ratecheck(last, &errinterval));
1108 }
1109 
1110 /*
1111  * Search for a vendor/product pair in an array.  The item size is
1112  * given as an argument.
1113  */
1114 const struct usb_devno *
1115 usb_match_device(const struct usb_devno *tbl, u_int nentries, u_int sz,
1116 		 u_int16_t vendor, u_int16_t product)
1117 {
1118 	while (nentries-- > 0) {
1119 		u_int16_t tproduct = tbl->ud_product;
1120 		if (tbl->ud_vendor == vendor &&
1121 		    (tproduct == product || tproduct == USB_PRODUCT_ANY))
1122 			return (tbl);
1123 		tbl = (const struct usb_devno *)((const char *)tbl + sz);
1124 	}
1125 	return (NULL);
1126 }
1127 
1128 
1129 void
1130 usb_desc_iter_init(usbd_device_handle dev, usbd_desc_iter_t *iter)
1131 {
1132 	const usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
1133 
1134         iter->cur = (const uByte *)cd;
1135         iter->end = (const uByte *)cd + UGETW(cd->wTotalLength);
1136 }
1137 
1138 const usb_descriptor_t *
1139 usb_desc_iter_next(usbd_desc_iter_t *iter)
1140 {
1141 	const usb_descriptor_t *desc;
1142 
1143 	if (iter->cur + sizeof(usb_descriptor_t) >= iter->end) {
1144 		if (iter->cur != iter->end)
1145 			printf("usb_desc_iter_next: bad descriptor\n");
1146 		return NULL;
1147 	}
1148 	desc = (const usb_descriptor_t *)iter->cur;
1149 	if (desc->bLength == 0) {
1150 		printf("usb_desc_iter_next: descriptor length = 0\n");
1151 		return NULL;
1152 	}
1153 	iter->cur += desc->bLength;
1154 	if (iter->cur > iter->end) {
1155 		printf("usb_desc_iter_next: descriptor length too large\n");
1156 		return NULL;
1157 	}
1158 	return desc;
1159 }
1160 
1161 usbd_status
1162 usbd_get_string(usbd_device_handle dev, int si, char *buf)
1163 {
1164 	return usbd_get_string0(dev, si, buf, 1);
1165 }
1166 
1167 usbd_status
1168 usbd_get_string0(usbd_device_handle dev, int si, char *buf, int unicode)
1169 {
1170 	int swap = dev->quirks->uq_flags & UQ_SWAP_UNICODE;
1171 	usb_string_descriptor_t us;
1172 	char *s;
1173 	int i, n;
1174 	u_int16_t c;
1175 	usbd_status err;
1176 	int size;
1177 
1178 	buf[0] = '\0';
1179 	if (si == 0)
1180 		return (USBD_INVAL);
1181 	if (dev->quirks->uq_flags & UQ_NO_STRINGS)
1182 		return (USBD_STALLED);
1183 	if (dev->langid == USBD_NOLANG) {
1184 		/* Set up default language */
1185 		err = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us,
1186 		    &size);
1187 		if (err || size < 4) {
1188 			DPRINTFN(-1,("usbd_get_string: getting lang failed, using 0\n"));
1189 			dev->langid = 0; /* Well, just pick something then */
1190 		} else {
1191 			/* Pick the first language as the default. */
1192 			dev->langid = UGETW(us.bString[0]);
1193 		}
1194 	}
1195 	err = usbd_get_string_desc(dev, si, dev->langid, &us, &size);
1196 	if (err)
1197 		return (err);
1198 	s = buf;
1199 	n = size / 2 - 1;
1200 	if (unicode) {
1201 		for (i = 0; i < n; i++) {
1202 			c = UGETW(us.bString[i]);
1203 			if (swap)
1204 				c = (c >> 8) | (c << 8);
1205 			s += wput_utf8(s, 3, c);
1206 		}
1207 		*s++ = 0;
1208 	}
1209 #ifdef COMPAT_30
1210 	else {
1211 		for (i = 0; i < n; i++) {
1212 			c = UGETW(us.bString[i]);
1213 			if (swap)
1214 				c = (c >> 8) | (c << 8);
1215 			*s++ = (c < 0x80) ? c : '?';
1216 		}
1217 		*s++ = 0;
1218 	}
1219 #endif
1220 	return (USBD_NORMAL_COMPLETION);
1221 }
1222 
1223 #if defined(__FreeBSD__)
1224 int
1225 usbd_driver_load(module_t mod, int what, void *arg)
1226 {
1227 	/* XXX should implement something like a function that removes all generic devices */
1228 
1229  	return (0);
1230 }
1231 
1232 #endif
1233