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