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