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