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