kernel: Fix two NULL dereference issues.
[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
4 /*
5  * Copyright (c) 1998 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *        This product includes software developed by the NetBSD
23  *        Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/module.h>
45 #include <sys/bus.h>
46 #include "usb_if.h"
47 #if defined(DIAGNOSTIC) && defined(__i386__)
48 #include <machine/cpu.h>
49 #endif
50 #include <sys/malloc.h>
51 #include <sys/proc.h>
52 #include <sys/thread2.h>
53
54 #include <bus/usb/usb.h>
55 #include <bus/usb/usbdi.h>
56 #include <bus/usb/usbdi_util.h>
57 #include <bus/usb/usbdivar.h>
58 #include <bus/usb/usb_mem.h>
59 #include <bus/usb/usb_quirks.h>
60
61 #define delay(d)        DELAY(d)
62
63 #ifdef USB_DEBUG
64 #define DPRINTF(x)      if (usbdebug) kprintf x
65 #define DPRINTFN(n,x)   if (usbdebug>(n)) kprintf x
66 extern int usbdebug;
67 #else
68 #define DPRINTF(x)
69 #define DPRINTFN(n,x)
70 #endif
71
72 static usbd_status usbd_ar_pipe(usbd_pipe_handle pipe);
73 static void usbd_do_request_async_cb
74         (usbd_xfer_handle, usbd_private_handle, usbd_status);
75 static void usbd_start_next(usbd_pipe_handle pipe);
76 static usbd_status usbd_open_pipe_ival
77         (usbd_interface_handle, u_int8_t, u_int8_t, usbd_pipe_handle *, int);
78 static int usbd_xfer_isread(usbd_xfer_handle xfer);
79
80 static int usbd_nbuses = 0;
81
82 void
83 usbd_init(void)
84 {
85         usbd_nbuses++;
86 }
87
88 void
89 usbd_finish(void)
90 {
91         --usbd_nbuses;
92 }
93
94 static __inline int
95 usbd_xfer_isread(usbd_xfer_handle xfer)
96 {
97         if (xfer->rqflags & URQ_REQUEST)
98                 return (xfer->request.bmRequestType & UT_READ);
99         else
100                 return (xfer->pipe->endpoint->edesc->bEndpointAddress &
101                         UE_DIR_IN);
102 }
103
104 #ifdef USB_DEBUG
105 void
106 usbd_dump_iface(struct usbd_interface *iface)
107 {
108         kprintf("usbd_dump_iface: iface=%p\n", iface);
109         if (iface == NULL)
110                 return;
111         kprintf(" device=%p idesc=%p index=%d altindex=%d priv=%p\n",
112                iface->device, iface->idesc, iface->index, iface->altindex,
113                iface->priv);
114 }
115
116 void
117 usbd_dump_device(struct usbd_device *dev)
118 {
119         kprintf("usbd_dump_device: dev=%p\n", dev);
120         if (dev == NULL)
121                 return;
122         kprintf(" bus=%p default_pipe=%p\n", dev->bus, dev->default_pipe);
123         kprintf(" address=%d config=%d depth=%d speed=%d self_powered=%d "
124                "power=%d langid=%d\n",
125                dev->address, dev->config, dev->depth, dev->speed,
126                dev->self_powered, dev->power, dev->langid);
127 }
128
129 void
130 usbd_dump_endpoint(struct usbd_endpoint *endp)
131 {
132         kprintf("usbd_dump_endpoint: endp=%p\n", endp);
133         if (endp == NULL)
134                 return;
135         kprintf(" edesc=%p refcnt=%d\n", endp->edesc, endp->refcnt);
136         if (endp->edesc)
137                 kprintf(" bEndpointAddress=0x%02x\n",
138                        endp->edesc->bEndpointAddress);
139 }
140
141 void
142 usbd_dump_queue(usbd_pipe_handle pipe)
143 {
144         usbd_xfer_handle xfer;
145
146         kprintf("usbd_dump_queue: pipe=%p\n", pipe);
147         STAILQ_FOREACH(xfer, &pipe->queue, next) {
148                 kprintf("  xfer=%p\n", xfer);
149         }
150 }
151
152 void
153 usbd_dump_pipe(usbd_pipe_handle pipe)
154 {
155         kprintf("usbd_dump_pipe: pipe=%p\n", pipe);
156         if (pipe == NULL)
157                 return;
158         usbd_dump_iface(pipe->iface);
159         usbd_dump_device(pipe->device);
160         usbd_dump_endpoint(pipe->endpoint);
161         kprintf(" (usbd_dump_pipe:)\n refcnt=%d running=%d aborting=%d\n",
162                pipe->refcnt, pipe->running, pipe->aborting);
163         kprintf(" intrxfer=%p, repeat=%d, interval=%d\n",
164                pipe->intrxfer, pipe->repeat, pipe->interval);
165 }
166 #endif
167
168 usbd_status
169 usbd_open_pipe(usbd_interface_handle iface, u_int8_t address,
170                u_int8_t flags, usbd_pipe_handle *pipe)
171 {
172         return (usbd_open_pipe_ival(iface, address, flags, pipe,
173                                     USBD_DEFAULT_INTERVAL));
174 }
175
176 usbd_status
177 usbd_open_pipe_ival(usbd_interface_handle iface, u_int8_t address,
178                     u_int8_t flags, usbd_pipe_handle *pipe, int ival)
179 {
180         usbd_pipe_handle p;
181         struct usbd_endpoint *ep;
182         usbd_status err;
183         int i;
184
185         DPRINTFN(3,("usbd_open_pipe: iface=%p address=0x%x flags=0x%x\n",
186                     iface, address, flags));
187
188         for (i = 0; i < iface->idesc->bNumEndpoints; i++) {
189                 ep = &iface->endpoints[i];
190                 if (ep->edesc == NULL)
191                         return (USBD_IOERROR);
192                 if (ep->edesc->bEndpointAddress == address)
193                         goto found;
194         }
195         return (USBD_BAD_ADDRESS);
196  found:
197         if ((flags & USBD_EXCLUSIVE_USE) && ep->refcnt != 0)
198                 return (USBD_IN_USE);
199         err = usbd_setup_pipe(iface->device, iface, ep, ival, &p);
200         if (err)
201                 return (err);
202         LIST_INSERT_HEAD(&iface->pipes, p, next);
203         *pipe = p;
204         return (USBD_NORMAL_COMPLETION);
205 }
206
207 usbd_status
208 usbd_open_pipe_intr(usbd_interface_handle iface, u_int8_t address,
209                     u_int8_t flags, usbd_pipe_handle *pipe,
210                     usbd_private_handle priv, void *buffer, u_int32_t len,
211                     usbd_callback cb, int ival)
212 {
213         usbd_status err;
214         usbd_xfer_handle xfer;
215         usbd_pipe_handle ipipe;
216
217         DPRINTFN(3,("usbd_open_pipe_intr: address=0x%x flags=0x%x len=%d\n",
218                     address, flags, len));
219
220         err = usbd_open_pipe_ival(iface, address, USBD_EXCLUSIVE_USE,
221                                   &ipipe, ival);
222         if (err)
223                 return (err);
224         xfer = usbd_alloc_xfer(iface->device);
225         if (xfer == NULL) {
226                 err = USBD_NOMEM;
227                 goto bad1;
228         }
229         usbd_setup_xfer(xfer, ipipe, priv, buffer, len, flags,
230             USBD_NO_TIMEOUT, cb);
231         ipipe->intrxfer = xfer;
232         ipipe->repeat = 1;
233         err = usbd_transfer(xfer);
234         *pipe = ipipe;
235         if (err != USBD_IN_PROGRESS && err)
236                 goto bad2;
237         return (USBD_NORMAL_COMPLETION);
238
239  bad2:
240         ipipe->intrxfer = NULL;
241         ipipe->repeat = 0;
242         usbd_free_xfer(xfer);
243  bad1:
244         usbd_close_pipe(ipipe);
245         return (err);
246 }
247
248 usbd_status
249 usbd_close_pipe(usbd_pipe_handle pipe)
250 {
251 #ifdef DIAGNOSTIC
252         if (pipe == NULL) {
253                 kprintf("usbd_close_pipe: pipe==NULL\n");
254                 return (USBD_NORMAL_COMPLETION);
255         }
256 #endif
257
258         if (--pipe->refcnt != 0)
259                 return (USBD_NORMAL_COMPLETION);
260         if (! STAILQ_EMPTY(&pipe->queue))
261                 return (USBD_PENDING_REQUESTS);
262         LIST_REMOVE(pipe, next);
263         pipe->endpoint->refcnt--;
264         pipe->methods->close(pipe);
265         if (pipe->intrxfer != NULL)
266                 usbd_free_xfer(pipe->intrxfer);
267         kfree(pipe, M_USB);
268         return (USBD_NORMAL_COMPLETION);
269 }
270
271 usbd_status
272 usbd_transfer(usbd_xfer_handle xfer)
273 {
274         usbd_pipe_handle pipe = xfer->pipe;
275         usb_dma_t *dmap = &xfer->dmabuf;
276         usbd_status err;
277         u_int size;
278         int didtry;
279
280         DPRINTFN(5,("usbd_transfer: xfer=%p, flags=%d, pipe=%p, running=%d\n",
281                     xfer, xfer->flags, pipe, pipe->running));
282 #ifdef USB_DEBUG
283         if (usbdebug > 5)
284                 usbd_dump_queue(pipe);
285 #endif
286         xfer->done = 0;
287
288         if (pipe->aborting)
289                 return (USBD_CANCELLED);
290
291         size = xfer->length;
292         /* If there is no buffer, allocate one. */
293         if (!(xfer->rqflags & URQ_DEV_DMABUF) && size != 0) {
294                 struct usbd_bus *bus = pipe->device->bus;
295
296 #ifdef DIAGNOSTIC
297                 if (xfer->rqflags & URQ_AUTO_DMABUF)
298                         kprintf("usbd_transfer: has old buffer!\n");
299 #endif
300                 err = bus->methods->allocm(bus, dmap, size);
301                 if (err)
302                         return (err);
303                 xfer->rqflags |= URQ_AUTO_DMABUF;
304         }
305
306         /* Copy data if going out. */
307         if (!(xfer->flags & USBD_NO_COPY) && size != 0 &&
308             !usbd_xfer_isread(xfer))
309                 memcpy(KERNADDR(dmap, 0), xfer->buffer, size);
310
311         err = pipe->methods->transfer(xfer);
312
313         if (err != USBD_IN_PROGRESS && err) {
314                 /* The transfer has not been queued, so free buffer. */
315                 if (xfer->rqflags & URQ_AUTO_DMABUF) {
316                         struct usbd_bus *bus = pipe->device->bus;
317
318                         bus->methods->freem(bus, &xfer->dmabuf);
319                         xfer->rqflags &= ~URQ_AUTO_DMABUF;
320                 }
321         }
322
323         if (!(xfer->flags & USBD_SYNCHRONOUS))
324                 return (err);
325
326         /* Sync transfer, wait for completion. */
327         if (err != USBD_IN_PROGRESS)
328                 return (err);
329         crit_enter();
330         didtry = 0;
331         while (!xfer->done) {
332                 if (pipe->device->bus->use_polling) {
333                         pipe->device->bus->methods->do_poll(pipe->device->bus);
334                         if (didtry++ == 0) {
335                                 kprintf("Warning: usbd_transfer: not done, "
336                                         "retrying.");
337                         } else {
338                                 if (didtry == 10)
339                                         usbd_abort_pipe(pipe);
340                                 kprintf(".");
341                         }
342                 }
343                 tsleep(xfer, 0, "usbsyn", hz);
344         }
345         if (didtry)
346                 kprintf(" ok\n");
347         crit_exit();
348         return (xfer->status);
349 }
350
351 /* Like usbd_transfer(), but waits for completion. */
352 usbd_status
353 usbd_sync_transfer(usbd_xfer_handle xfer)
354 {
355         xfer->flags |= USBD_SYNCHRONOUS;
356         return (usbd_transfer(xfer));
357 }
358
359 void *
360 usbd_alloc_buffer(usbd_xfer_handle xfer, u_int32_t size)
361 {
362         struct usbd_bus *bus = xfer->device->bus;
363         usbd_status err;
364
365 #ifdef DIAGNOSTIC
366         if (xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))
367                 kprintf("usbd_alloc_buffer: xfer already has a buffer\n");
368 #endif
369         err = bus->methods->allocm(bus, &xfer->dmabuf, size);
370         if (err) {
371                 device_printf(bus->bdev, "Unable to allocate %u contig\n",
372                               size);
373                 return (NULL);
374         }
375         xfer->rqflags |= URQ_DEV_DMABUF;
376         return (KERNADDR(&xfer->dmabuf, 0));
377 }
378
379 void
380 usbd_free_buffer(usbd_xfer_handle xfer)
381 {
382 #ifdef DIAGNOSTIC
383         if (!(xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))) {
384                 kprintf("usbd_free_buffer: no buffer\n");
385                 return;
386         }
387 #endif
388         xfer->rqflags &= ~(URQ_DEV_DMABUF | URQ_AUTO_DMABUF);
389         xfer->device->bus->methods->freem(xfer->device->bus, &xfer->dmabuf);
390 }
391
392 void *
393 usbd_get_buffer(usbd_xfer_handle xfer)
394 {
395         if (!(xfer->rqflags & URQ_DEV_DMABUF))
396                 return (0);
397         return (KERNADDR(&xfer->dmabuf, 0));
398 }
399
400 usbd_xfer_handle
401 usbd_alloc_xfer(usbd_device_handle dev)
402 {
403         usbd_xfer_handle xfer;
404
405         xfer = dev->bus->methods->allocx(dev->bus);
406         if (xfer == NULL)
407                 return (NULL);
408         xfer->device = dev;
409         callout_init(&xfer->timeout_handle);
410         DPRINTFN(5,("usbd_alloc_xfer() = %p\n", xfer));
411         return (xfer);
412 }
413
414 usbd_status
415 usbd_free_xfer(usbd_xfer_handle xfer)
416 {
417         DPRINTFN(5,("usbd_free_xfer: %p\n", xfer));
418         if (xfer->rqflags & (URQ_DEV_DMABUF | URQ_AUTO_DMABUF))
419                 usbd_free_buffer(xfer);
420         xfer->device->bus->methods->freex(xfer->device->bus, xfer);
421         return (USBD_NORMAL_COMPLETION);
422 }
423
424 void
425 usbd_setup_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
426                 usbd_private_handle priv, void *buffer, u_int32_t length,
427                 u_int16_t flags, u_int32_t timeout,
428                 usbd_callback callback)
429 {
430         xfer->pipe = pipe;
431         xfer->priv = priv;
432         xfer->buffer = buffer;
433         xfer->length = length;
434         xfer->actlen = 0;
435         xfer->flags = flags;
436         xfer->timeout = timeout;
437         xfer->status = USBD_NOT_STARTED;
438         xfer->callback = callback;
439         xfer->rqflags &= ~URQ_REQUEST;
440         xfer->nframes = 0;
441 }
442
443 void
444 usbd_setup_default_xfer(usbd_xfer_handle xfer, usbd_device_handle dev,
445                         usbd_private_handle priv, u_int32_t timeout,
446                         usb_device_request_t *req, void *buffer,
447                         u_int32_t length, u_int16_t flags,
448                         usbd_callback callback)
449 {
450         xfer->pipe = dev->default_pipe;
451         xfer->priv = priv;
452         xfer->buffer = buffer;
453         xfer->length = length;
454         xfer->actlen = 0;
455         xfer->flags = flags;
456         xfer->timeout = timeout;
457         xfer->status = USBD_NOT_STARTED;
458         xfer->callback = callback;
459         xfer->request = *req;
460         xfer->rqflags |= URQ_REQUEST;
461         xfer->nframes = 0;
462 }
463
464 void
465 usbd_setup_isoc_xfer(usbd_xfer_handle xfer, usbd_pipe_handle pipe,
466                      usbd_private_handle priv, u_int16_t *frlengths,
467                      u_int32_t nframes, u_int16_t flags, usbd_callback callback)
468 {
469         xfer->pipe = pipe;
470         xfer->priv = priv;
471         xfer->buffer = 0;
472         xfer->length = 0;
473         xfer->actlen = 0;
474         xfer->flags = flags;
475         xfer->timeout = USBD_NO_TIMEOUT;
476         xfer->status = USBD_NOT_STARTED;
477         xfer->callback = callback;
478         xfer->rqflags &= ~URQ_REQUEST;
479         xfer->frlengths = frlengths;
480         xfer->nframes = nframes;
481 }
482
483 void
484 usbd_get_xfer_status(usbd_xfer_handle xfer, usbd_private_handle *priv,
485                      void **buffer, u_int32_t *count, usbd_status *status)
486 {
487         if (priv != NULL)
488                 *priv = xfer->priv;
489         if (buffer != NULL)
490                 *buffer = xfer->buffer;
491         if (count != NULL)
492                 *count = xfer->actlen;
493         if (status != NULL)
494                 *status = xfer->status;
495 }
496
497 int
498 usbd_get_speed(usbd_device_handle dev)
499 {
500         return(dev->speed);
501 }
502
503 usb_config_descriptor_t *
504 usbd_get_config_descriptor(usbd_device_handle dev)
505 {
506 #ifdef DIAGNOSTIC
507         if (dev == NULL) {
508                 kprintf("usbd_get_config_descriptor: dev == NULL\n");
509                 return (NULL);
510         }
511 #endif
512         return (dev->cdesc);
513 }
514
515 usb_interface_descriptor_t *
516 usbd_get_interface_descriptor(usbd_interface_handle iface)
517 {
518 #ifdef DIAGNOSTIC
519         if (iface == NULL) {
520                 kprintf("usbd_get_interface_descriptor: dev == NULL\n");
521                 return (NULL);
522         }
523 #endif
524         return (iface->idesc);
525 }
526
527 usb_device_descriptor_t *
528 usbd_get_device_descriptor(usbd_device_handle dev)
529 {
530         return (&dev->ddesc);
531 }
532
533 usb_endpoint_descriptor_t *
534 usbd_interface2endpoint_descriptor(usbd_interface_handle iface, u_int8_t index)
535 {
536         if (index >= iface->idesc->bNumEndpoints)
537                 return (0);
538         return (iface->endpoints[index].edesc);
539 }
540
541 usbd_status
542 usbd_abort_pipe(usbd_pipe_handle pipe)
543 {
544         usbd_status err;
545
546 #ifdef DIAGNOSTIC
547         if (pipe == NULL) {
548                 kprintf("usbd_close_pipe: pipe==NULL\n");
549                 return (USBD_NORMAL_COMPLETION);
550         }
551 #endif
552         crit_enter();
553         err = usbd_ar_pipe(pipe);
554         crit_exit();
555         return (err);
556 }
557
558 usbd_status
559 usbd_abort_default_pipe(usbd_device_handle dev)
560 {
561         return (usbd_abort_pipe(dev->default_pipe));
562 }
563
564 usbd_status
565 usbd_clear_endpoint_stall(usbd_pipe_handle pipe)
566 {
567         usbd_device_handle dev = pipe->device;
568         usb_device_request_t req;
569         usbd_status err;
570
571         DPRINTFN(8, ("usbd_clear_endpoint_stall\n"));
572
573         /*
574          * Clearing en endpoint stall resets the endpoint toggle, so
575          * do the same to the HC toggle.
576          */
577         pipe->methods->cleartoggle(pipe);
578
579         req.bmRequestType = UT_WRITE_ENDPOINT;
580         req.bRequest = UR_CLEAR_FEATURE;
581         USETW(req.wValue, UF_ENDPOINT_HALT);
582         USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
583         USETW(req.wLength, 0);
584         err = usbd_do_request(dev, &req, 0);
585 #if 0
586 XXX should we do this?
587         if (!err) {
588                 pipe->state = USBD_PIPE_ACTIVE;
589                 /* XXX activate pipe */
590         }
591 #endif
592         return (err);
593 }
594
595 usbd_status
596 usbd_clear_endpoint_stall_async(usbd_pipe_handle pipe)
597 {
598         usbd_device_handle dev = pipe->device;
599         usb_device_request_t req;
600         usbd_status err;
601
602         pipe->methods->cleartoggle(pipe);
603
604         req.bmRequestType = UT_WRITE_ENDPOINT;
605         req.bRequest = UR_CLEAR_FEATURE;
606         USETW(req.wValue, UF_ENDPOINT_HALT);
607         USETW(req.wIndex, pipe->endpoint->edesc->bEndpointAddress);
608         USETW(req.wLength, 0);
609         err = usbd_do_request_async(dev, &req, 0);
610         return (err);
611 }
612
613 void
614 usbd_clear_endpoint_toggle(usbd_pipe_handle pipe)
615 {
616         pipe->methods->cleartoggle(pipe);
617 }
618
619 usbd_status
620 usbd_endpoint_count(usbd_interface_handle iface, u_int8_t *count)
621 {
622 #ifdef DIAGNOSTIC
623         if (iface == NULL || iface->idesc == NULL) {
624                 kprintf("usbd_endpoint_count: NULL pointer\n");
625                 return (USBD_INVAL);
626         }
627 #endif
628         *count = iface->idesc->bNumEndpoints;
629         return (USBD_NORMAL_COMPLETION);
630 }
631
632 usbd_status
633 usbd_interface_count(usbd_device_handle dev, u_int8_t *count)
634 {
635         if (dev->cdesc == NULL)
636                 return (USBD_NOT_CONFIGURED);
637         *count = dev->cdesc->bNumInterface;
638         return (USBD_NORMAL_COMPLETION);
639 }
640
641 void
642 usbd_interface2device_handle(usbd_interface_handle iface,
643                              usbd_device_handle *dev)
644 {
645         *dev = iface->device;
646 }
647
648 usbd_status
649 usbd_device2interface_handle(usbd_device_handle dev,
650                              u_int8_t ifaceno, usbd_interface_handle *iface)
651 {
652         if (dev->cdesc == NULL)
653                 return (USBD_NOT_CONFIGURED);
654         if (ifaceno >= dev->cdesc->bNumInterface)
655                 return (USBD_INVAL);
656         *iface = &dev->ifaces[ifaceno];
657         return (USBD_NORMAL_COMPLETION);
658 }
659
660 usbd_device_handle
661 usbd_pipe2device_handle(usbd_pipe_handle pipe)
662 {
663         return (pipe->device);
664 }
665
666 /* XXXX use altno */
667 usbd_status
668 usbd_set_interface(usbd_interface_handle iface, int altidx)
669 {
670         usb_device_request_t req;
671         usbd_status err;
672         void *endpoints;
673
674         if (LIST_FIRST(&iface->pipes) != 0)
675                 return (USBD_IN_USE);
676
677         endpoints = iface->endpoints;
678         err = usbd_fill_iface_data(iface->device, iface->index, altidx);
679         if (err)
680                 return (err);
681
682         /* new setting works, we can free old endpoints */
683         if (endpoints != NULL)
684                 kfree(endpoints, M_USB);
685
686 #ifdef DIAGNOSTIC
687         if (iface->idesc == NULL) {
688                 kprintf("usbd_set_interface: NULL pointer\n");
689                 return (USBD_INVAL);
690         }
691 #endif
692
693         req.bmRequestType = UT_WRITE_INTERFACE;
694         req.bRequest = UR_SET_INTERFACE;
695         USETW(req.wValue, iface->idesc->bAlternateSetting);
696         USETW(req.wIndex, iface->idesc->bInterfaceNumber);
697         USETW(req.wLength, 0);
698         return (usbd_do_request(iface->device, &req, 0));
699 }
700
701 int
702 usbd_get_no_alts(usb_config_descriptor_t *cdesc, int ifaceno)
703 {
704         char *p = (char *)cdesc;
705         char *end = p + UGETW(cdesc->wTotalLength);
706         usb_interface_descriptor_t *d;
707         int n;
708
709         for (n = 0; p < end; p += d->bLength) {
710                 d = (usb_interface_descriptor_t *)p;
711                 if (p + d->bLength <= end &&
712                     d->bDescriptorType == UDESC_INTERFACE &&
713                     d->bInterfaceNumber == ifaceno)
714                         n++;
715         }
716         return (n);
717 }
718
719 int
720 usbd_get_interface_altindex(usbd_interface_handle iface)
721 {
722         return (iface->altindex);
723 }
724
725 usbd_status
726 usbd_get_interface(usbd_interface_handle iface, u_int8_t *aiface)
727 {
728         usb_device_request_t req;
729
730         req.bmRequestType = UT_READ_INTERFACE;
731         req.bRequest = UR_GET_INTERFACE;
732         USETW(req.wValue, 0);
733         USETW(req.wIndex, iface->idesc->bInterfaceNumber);
734         USETW(req.wLength, 1);
735         return (usbd_do_request(iface->device, &req, aiface));
736 }
737
738 /*** Internal routines ***/
739
740 /* Dequeue all pipe operations, called from critical section. */
741 static usbd_status
742 usbd_ar_pipe(usbd_pipe_handle pipe)
743 {
744         usbd_xfer_handle xfer;
745
746         DPRINTFN(2,("usbd_ar_pipe: pipe=%p\n", pipe));
747 #ifdef USB_DEBUG
748         if (usbdebug > 5)
749                 usbd_dump_queue(pipe);
750 #endif
751         pipe->repeat = 0;
752         pipe->aborting = 1;
753         while ((xfer = STAILQ_FIRST(&pipe->queue)) != NULL) {
754                 DPRINTFN(2,("usbd_ar_pipe: pipe=%p xfer=%p (methods=%p)\n",
755                             pipe, xfer, pipe->methods));
756                 /* Make the HC abort it (and invoke the callback). */
757                 pipe->methods->abort(xfer);
758                 /* XXX only for non-0 usbd_clear_endpoint_stall(pipe); */
759         }
760         pipe->aborting = 0;
761         return (USBD_NORMAL_COMPLETION);
762 }
763
764 /* Called from critical section */
765 void
766 usb_transfer_complete(usbd_xfer_handle xfer)
767 {
768         usbd_pipe_handle pipe = xfer->pipe;
769         usb_dma_t *dmap = &xfer->dmabuf;
770         int sync = xfer->flags & USBD_SYNCHRONOUS;
771         int erred = xfer->status == USBD_CANCELLED ||
772             xfer->status == USBD_TIMEOUT;
773         int repeat;
774         int polling;
775
776         DPRINTFN(5, ("usb_transfer_complete: pipe=%p xfer=%p status=%d "
777                      "actlen=%d\n", pipe, xfer, xfer->status, xfer->actlen));
778 #ifdef DIAGNOSTIC
779         if (xfer->busy_free != XFER_ONQU) {
780                 kprintf("usb_transfer_complete: xfer=%p not busy 0x%08x\n",
781                        xfer, xfer->busy_free);
782                 return;
783         }
784 #endif
785
786 #ifdef DIAGNOSTIC
787         if (pipe == NULL) {
788                 kprintf("usbd_transfer_cb: pipe==0, xfer=%p\n", xfer);
789                 return;
790         }
791 #endif
792         repeat = pipe->repeat;
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