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