Initial import from FreeBSD RELENG_4:
[games.git] / sys / dev / usbmisc / ugen / ugen.c
1 /*      $NetBSD: ugen.c,v 1.27 1999/10/28 12:08:38 augustss Exp $       */
2 /*      $FreeBSD: src/sys/dev/usb/ugen.c,v 1.38.2.9 2002/11/06 14:41:01 joe 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
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/malloc.h>
46 #if defined(__NetBSD__) || defined(__OpenBSD__)
47 #include <sys/device.h>
48 #include <sys/ioctl.h>
49 #elif defined(__FreeBSD__)
50 #include <sys/module.h>
51 #include <sys/bus.h>
52 #include <sys/ioccom.h>
53 #include <sys/conf.h>
54 #include <sys/fcntl.h>
55 #include <sys/filio.h>
56 #endif
57 #include <sys/tty.h>
58 #include <sys/file.h>
59 #include <sys/select.h>
60 #include <sys/proc.h>
61 #include <sys/vnode.h>
62 #include <sys/poll.h>
63 #include <sys/sysctl.h>
64
65 #include <dev/usb/usb.h>
66 #include <dev/usb/usbdi.h>
67 #include <dev/usb/usbdi_util.h>
68
69 #ifdef USB_DEBUG
70 #define DPRINTF(x)      if (ugendebug) logprintf x
71 #define DPRINTFN(n,x)   if (ugendebug>(n)) logprintf x
72 int     ugendebug = 0;
73 SYSCTL_NODE(_hw_usb, OID_AUTO, ugen, CTLFLAG_RW, 0, "USB ugen");
74 SYSCTL_INT(_hw_usb_ugen, OID_AUTO, debug, CTLFLAG_RW,
75            &ugendebug, 0, "ugen debug level");
76 #else
77 #define DPRINTF(x)
78 #define DPRINTFN(n,x)
79 #endif
80
81 #define UGEN_CHUNK      128     /* chunk size for read */
82 #define UGEN_IBSIZE     1020    /* buffer size */
83 #define UGEN_BBSIZE     1024
84
85 #define UGEN_NISOFRAMES 500     /* 0.5 seconds worth */
86 #define UGEN_NISOREQS   6       /* number of outstanding xfer requests */
87 #define UGEN_NISORFRMS  4       /* number of frames (miliseconds) per req */
88
89 struct ugen_endpoint {
90         struct ugen_softc *sc;
91         usb_endpoint_descriptor_t *edesc;
92         usbd_interface_handle iface;
93         int state;
94 #define UGEN_ASLP       0x02    /* waiting for data */
95 #define UGEN_SHORT_OK   0x04    /* short xfers are OK */
96         usbd_pipe_handle pipeh;
97         struct clist q;
98         struct selinfo rsel;
99         u_char *ibuf;           /* start of buffer (circular for isoc) */
100         u_char *fill;           /* location for input (isoc) */
101         u_char *limit;          /* end of circular buffer (isoc) */
102         u_char *cur;            /* current read location (isoc) */
103         u_int32_t timeout;
104         struct isoreq {
105                 struct ugen_endpoint *sce;
106                 usbd_xfer_handle xfer;
107                 void *dmabuf;
108                 u_int16_t sizes[UGEN_NISORFRMS];
109         } isoreqs[UGEN_NISOREQS];
110 };
111
112 struct ugen_softc {
113         USBBASEDEVICE sc_dev;           /* base device */
114         usbd_device_handle sc_udev;
115
116         char sc_is_open[USB_MAX_ENDPOINTS];
117         struct ugen_endpoint sc_endpoints[USB_MAX_ENDPOINTS][2];
118 #define OUT 0
119 #define IN  1
120
121         int sc_refcnt;
122         u_char sc_dying;
123 };
124
125 #if defined(__NetBSD__) || defined(__OpenBSD__)
126 cdev_decl(ugen);
127 #elif defined(__FreeBSD__)
128 d_open_t  ugenopen;
129 d_close_t ugenclose;
130 d_read_t  ugenread;
131 d_write_t ugenwrite;
132 d_ioctl_t ugenioctl;
133 d_poll_t  ugenpoll;
134
135 #define UGEN_CDEV_MAJOR 114
136
137 Static struct cdevsw ugen_cdevsw = {
138         /* open */      ugenopen,
139         /* close */     ugenclose,
140         /* read */      ugenread,
141         /* write */     ugenwrite,
142         /* ioctl */     ugenioctl,
143         /* poll */      ugenpoll,
144         /* mmap */      nommap,
145         /* strategy */  nostrategy,
146         /* name */      "ugen",
147         /* maj */       UGEN_CDEV_MAJOR,
148         /* dump */      nodump,
149         /* psize */     nopsize,
150         /* flags */     0,
151         /* bmaj */      -1
152 };
153 #endif
154
155 Static void ugenintr(usbd_xfer_handle xfer, usbd_private_handle addr, 
156                           usbd_status status);
157 Static void ugen_isoc_rintr(usbd_xfer_handle xfer, usbd_private_handle addr,
158                             usbd_status status);
159 Static int ugen_do_read(struct ugen_softc *, int, struct uio *, int);
160 Static int ugen_do_write(struct ugen_softc *, int, struct uio *, int);
161 Static int ugen_do_ioctl(struct ugen_softc *, int, u_long, 
162                               caddr_t, int, usb_proc_ptr);
163 Static int ugen_set_config(struct ugen_softc *sc, int configno);
164 Static usb_config_descriptor_t *ugen_get_cdesc(struct ugen_softc *sc,
165                                                     int index, int *lenp);
166 Static usbd_status ugen_set_interface(struct ugen_softc *, int, int);
167 Static int ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx);
168
169 #define UGENUNIT(n) ((minor(n) >> 4) & 0xf)
170 #define UGENENDPOINT(n) (minor(n) & 0xf)
171 #define UGENMINOR(u, e) (((u) << 4) | (e))
172
173 USB_DECLARE_DRIVER(ugen);
174
175 USB_MATCH(ugen)
176 {
177         USB_MATCH_START(ugen, uaa);
178
179         if (uaa->usegeneric)
180                 return (UMATCH_GENERIC);
181         else
182                 return (UMATCH_NONE);
183 }
184
185 USB_ATTACH(ugen)
186 {
187         USB_ATTACH_START(ugen, sc, uaa);
188         usbd_device_handle udev;
189         char devinfo[1024];
190         usbd_status err;
191         int conf;
192         
193         usbd_devinfo(uaa->device, 0, devinfo);
194         USB_ATTACH_SETUP;
195         printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
196
197         sc->sc_udev = udev = uaa->device;
198
199         memset(sc->sc_endpoints, 0, sizeof sc->sc_endpoints);
200
201         /* First set configuration index 0, the default one for ugen. */
202         err = usbd_set_config_index(udev, 0, 0);
203         if (err) {
204                 printf("%s: setting configuration index 0 failed\n", 
205                        USBDEVNAME(sc->sc_dev));
206                 sc->sc_dying = 1;
207                 USB_ATTACH_ERROR_RETURN;
208         }
209         conf = usbd_get_config_descriptor(udev)->bConfigurationValue;
210
211         /* Set up all the local state for this configuration. */
212         err = ugen_set_config(sc, conf);
213         if (err) {
214                 printf("%s: setting configuration %d failed\n", 
215                        USBDEVNAME(sc->sc_dev), conf);
216                 sc->sc_dying = 1;
217                 USB_ATTACH_ERROR_RETURN;
218         }
219
220         USB_ATTACH_SUCCESS_RETURN;
221 }
222
223 Static int
224 ugen_set_config(struct ugen_softc *sc, int configno)
225 {
226         usbd_device_handle dev = sc->sc_udev;
227         usbd_interface_handle iface;
228         usb_endpoint_descriptor_t *ed;
229         struct ugen_endpoint *sce;
230         u_int8_t niface, nendpt;
231         int ifaceno, endptno, endpt;
232         usbd_status err;
233         int dir;
234
235         DPRINTFN(1,("ugen_set_config: %s to configno %d, sc=%p\n",
236                     USBDEVNAME(sc->sc_dev), configno, sc));
237
238         /* We start at 1, not 0, because we don't care whether the
239          * control endpoint is open or not. It is always present.
240          */
241         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++)
242                 if (sc->sc_is_open[endptno]) {
243                         DPRINTFN(1,
244                              ("ugen_set_config: %s - endpoint %d is open\n",
245                               USBDEVNAME(sc->sc_dev), endptno));
246                         return (USBD_IN_USE);
247                 }
248
249         if (usbd_get_config_descriptor(dev)->bConfigurationValue != configno) {
250                 /* Avoid setting the current value. */
251                 err = usbd_set_config_no(dev, configno, 0);
252                 if (err)
253                         return (err);
254         }
255
256         err = usbd_interface_count(dev, &niface);
257         if (err)
258                 return (err);
259         memset(sc->sc_endpoints, 0, sizeof sc->sc_endpoints);
260         for (ifaceno = 0; ifaceno < niface; ifaceno++) {
261                 DPRINTFN(1,("ugen_set_config: ifaceno %d\n", ifaceno));
262                 err = usbd_device2interface_handle(dev, ifaceno, &iface);
263                 if (err)
264                         return (err);
265                 err = usbd_endpoint_count(iface, &nendpt);
266                 if (err)
267                         return (err);
268                 for (endptno = 0; endptno < nendpt; endptno++) {
269                         ed = usbd_interface2endpoint_descriptor(iface,endptno);
270                         endpt = UE_GET_ADDR(ed->bEndpointAddress);
271                         dir = UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN?
272                                         IN : OUT;
273
274                         sce = &sc->sc_endpoints[endpt][dir];
275                         DPRINTFN(1,("ugen_set_config: endptno %d, endpt=0x%02x"
276                                     "(%d,%d), sce=%p\n", 
277                                     endptno, endpt, endpt, dir, sce));
278
279                         sce->sc = sc;
280                         sce->edesc = ed;
281                         sce->iface = iface;
282                 }
283         }
284
285
286 #if defined(__FreeBSD__)
287         /* the main device, ctrl endpoint */
288         make_dev(&ugen_cdevsw, UGENMINOR(USBDEVUNIT(sc->sc_dev), 0),
289                 UID_ROOT, GID_OPERATOR, 0644, "%s", USBDEVNAME(sc->sc_dev));
290
291         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
292                 if (sc->sc_endpoints[endptno][IN].sc != NULL ||
293                     sc->sc_endpoints[endptno][OUT].sc != NULL ) {
294                         /* endpt can be 0x81 and 0x01, representing
295                          * endpoint address 0x01 and IN/OUT directions.
296                          * We map both endpts to the same device,
297                          * IN is reading from it, OUT is writing to it.
298                          *
299                          * In the if clause above we check whether one
300                          * of the structs is populated.
301                          */
302                         make_dev(&ugen_cdevsw,
303                                 UGENMINOR(USBDEVUNIT(sc->sc_dev), endptno),
304                                 UID_ROOT, GID_OPERATOR, 0644,
305                                 "%s.%d",
306                                 USBDEVNAME(sc->sc_dev), endptno);
307                 }
308         }
309 #endif
310
311         return (USBD_NORMAL_COMPLETION);
312 }
313
314 int
315 ugenopen(dev_t dev, int flag, int mode, usb_proc_ptr p)
316 {
317         struct ugen_softc *sc;
318         int unit = UGENUNIT(dev);
319         int endpt = UGENENDPOINT(dev);
320         usb_endpoint_descriptor_t *edesc;
321         struct ugen_endpoint *sce;
322         int dir, isize;
323         usbd_status err;
324         usbd_xfer_handle xfer;
325         void *buf;
326         int i, j;
327
328         USB_GET_SC_OPEN(ugen, unit, sc);
329
330         DPRINTFN(5, ("ugenopen: flag=%d, mode=%d, unit=%d endpt=%d\n", 
331                      flag, mode, unit, endpt));
332
333         if (sc == NULL || sc->sc_dying)
334                 return (ENXIO);
335
336         if (sc->sc_is_open[endpt])
337                 return (EBUSY);
338
339         if (endpt == USB_CONTROL_ENDPOINT) {
340                 sc->sc_is_open[USB_CONTROL_ENDPOINT] = 1;
341                 return (0);
342         }
343
344         /* Make sure there are pipes for all directions. */
345         for (dir = OUT; dir <= IN; dir++) {
346                 if (flag & (dir == OUT ? FWRITE : FREAD)) {
347                         sce = &sc->sc_endpoints[endpt][dir];
348                         if (sce == 0 || sce->edesc == 0)
349                                 return (ENXIO);
350                 }
351         }
352
353         /* Actually open the pipes. */
354         /* XXX Should back out properly if it fails. */
355         for (dir = OUT; dir <= IN; dir++) {
356                 if (!(flag & (dir == OUT ? FWRITE : FREAD)))
357                         continue;
358                 sce = &sc->sc_endpoints[endpt][dir];
359                 sce->state = 0;
360                 sce->timeout = USBD_NO_TIMEOUT;
361                 DPRINTFN(5, ("ugenopen: sc=%p, endpt=%d, dir=%d, sce=%p\n", 
362                              sc, endpt, dir, sce));
363                 edesc = sce->edesc;
364                 switch (edesc->bmAttributes & UE_XFERTYPE) {
365                 case UE_INTERRUPT:
366                         isize = UGETW(edesc->wMaxPacketSize);
367                         if (isize == 0) /* shouldn't happen */
368                                 return (EINVAL);
369                         sce->ibuf = malloc(isize, M_USBDEV, M_WAITOK);
370                         DPRINTFN(5, ("ugenopen: intr endpt=%d,isize=%d\n", 
371                                      endpt, isize));
372                         if (clalloc(&sce->q, UGEN_IBSIZE, 0) == -1)
373                                 return (ENOMEM);
374                         err = usbd_open_pipe_intr(sce->iface, 
375                                 edesc->bEndpointAddress, 
376                                 USBD_SHORT_XFER_OK, &sce->pipeh, sce, 
377                                 sce->ibuf, isize, ugenintr,
378                                 USBD_DEFAULT_INTERVAL);
379                         if (err) {
380                                 free(sce->ibuf, M_USBDEV);
381                                 clfree(&sce->q);
382                                 return (EIO);
383                         }
384                         DPRINTFN(5, ("ugenopen: interrupt open done\n"));
385                         break;
386                 case UE_BULK:
387                         err = usbd_open_pipe(sce->iface, 
388                                   edesc->bEndpointAddress, 0, &sce->pipeh);
389                         if (err)
390                                 return (EIO);
391                         break;
392                 case UE_ISOCHRONOUS:
393                         if (dir == OUT)
394                                 return (EINVAL);
395                         isize = UGETW(edesc->wMaxPacketSize);
396                         if (isize == 0) /* shouldn't happen */
397                                 return (EINVAL);
398                         sce->ibuf = malloc(isize * UGEN_NISOFRAMES,
399                                 M_USBDEV, M_WAITOK);
400                         sce->cur = sce->fill = sce->ibuf;
401                         sce->limit = sce->ibuf + isize * UGEN_NISOFRAMES;
402                         DPRINTFN(5, ("ugenopen: isoc endpt=%d, isize=%d\n", 
403                                      endpt, isize));
404                         err = usbd_open_pipe(sce->iface,
405                                   edesc->bEndpointAddress, 0, &sce->pipeh);
406                         if (err) {
407                                 free(sce->ibuf, M_USBDEV);
408                                 return (EIO);
409                         }
410                         for(i = 0; i < UGEN_NISOREQS; ++i) {
411                                 sce->isoreqs[i].sce = sce;
412                                 xfer = usbd_alloc_xfer(sc->sc_udev);
413                                 if (xfer == 0)
414                                         goto bad;
415                                 sce->isoreqs[i].xfer = xfer;
416                                 buf = usbd_alloc_buffer
417                                         (xfer, isize * UGEN_NISORFRMS);
418                                 if (buf == 0) {
419                                         i++;
420                                         goto bad;
421                                 }
422                                 sce->isoreqs[i].dmabuf = buf;
423                                 for(j = 0; j < UGEN_NISORFRMS; ++j)
424                                         sce->isoreqs[i].sizes[j] = isize;
425                                 usbd_setup_isoc_xfer
426                                         (xfer, sce->pipeh, &sce->isoreqs[i],
427                                          sce->isoreqs[i].sizes,
428                                          UGEN_NISORFRMS, USBD_NO_COPY,
429                                          ugen_isoc_rintr);
430                                 (void)usbd_transfer(xfer);
431                         }
432                         DPRINTFN(5, ("ugenopen: isoc open done\n"));
433                         break;
434                 bad:
435                         while (--i >= 0) /* implicit buffer free */
436                                 usbd_free_xfer(sce->isoreqs[i].xfer);
437                         return (ENOMEM);
438                 case UE_CONTROL:
439                         return (EINVAL);
440                 }
441         }
442         sc->sc_is_open[endpt] = 1;
443         return (0);
444 }
445
446 int
447 ugenclose(dev_t dev, int flag, int mode, usb_proc_ptr p)
448 {
449         int endpt = UGENENDPOINT(dev);
450         struct ugen_softc *sc;
451         struct ugen_endpoint *sce;
452         int dir;
453         int i;
454
455         USB_GET_SC(ugen, UGENUNIT(dev), sc);
456
457         DPRINTFN(5, ("ugenclose: flag=%d, mode=%d, unit=%d, endpt=%d\n",
458                      flag, mode, UGENUNIT(dev), endpt));
459
460 #ifdef DIAGNOSTIC
461         if (!sc->sc_is_open[endpt]) {
462                 printf("ugenclose: not open\n");
463                 return (EINVAL);
464         }
465 #endif
466
467         if (endpt == USB_CONTROL_ENDPOINT) {
468                 DPRINTFN(5, ("ugenclose: close control\n"));
469                 sc->sc_is_open[endpt] = 0;
470                 return (0);
471         }
472
473         for (dir = OUT; dir <= IN; dir++) {
474                 if (!(flag & (dir == OUT ? FWRITE : FREAD)))
475                         continue;
476                 sce = &sc->sc_endpoints[endpt][dir];
477                 if (sce == NULL || sce->pipeh == NULL)
478                         continue;
479                 DPRINTFN(5, ("ugenclose: endpt=%d dir=%d sce=%p\n", 
480                              endpt, dir, sce));
481
482                 usbd_abort_pipe(sce->pipeh);
483                 usbd_close_pipe(sce->pipeh);
484                 sce->pipeh = NULL;
485
486                 switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
487                 case UE_INTERRUPT:
488                         ndflush(&sce->q, sce->q.c_cc);
489                         clfree(&sce->q);
490                         break;
491                 case UE_ISOCHRONOUS:
492                         for (i = 0; i < UGEN_NISOREQS; ++i)
493                                 usbd_free_xfer(sce->isoreqs[i].xfer);
494                 default:
495                         break;
496                 }
497
498                 if (sce->ibuf != NULL) {
499                         free(sce->ibuf, M_USBDEV);
500                         sce->ibuf = NULL;
501                 }
502         }
503         sc->sc_is_open[endpt] = 0;
504
505         return (0);
506 }
507
508 Static int
509 ugen_do_read(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
510 {
511         struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][IN];
512         u_int32_t n, tn;
513         char buf[UGEN_BBSIZE];
514         usbd_xfer_handle xfer;
515         usbd_status err;
516         int s;
517         int error = 0;
518         u_char buffer[UGEN_CHUNK];
519
520         DPRINTFN(5, ("%s: ugenread: %d\n", USBDEVNAME(sc->sc_dev), endpt));
521
522         if (sc->sc_dying)
523                 return (EIO);
524
525         if (endpt == USB_CONTROL_ENDPOINT)
526                 return (ENODEV);
527
528 #ifdef DIAGNOSTIC
529         if (sce->edesc == NULL) {
530                 printf("ugenread: no edesc\n");
531                 return (EIO);
532         }
533         if (sce->pipeh == NULL) {
534                 printf("ugenread: no pipe\n");
535                 return (EIO);
536         }
537 #endif
538
539         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
540         case UE_INTERRUPT:
541                 /* Block until activity occured. */
542                 s = splusb();
543                 while (sce->q.c_cc == 0) {
544                         if (flag & IO_NDELAY) {
545                                 splx(s);
546                                 return (EWOULDBLOCK);
547                         }
548                         sce->state |= UGEN_ASLP;
549                         DPRINTFN(5, ("ugenread: sleep on %p\n", sc));
550                         error = tsleep(sce, PZERO | PCATCH, "ugenri", 0);
551                         DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
552                         if (sc->sc_dying)
553                                 error = EIO;
554                         if (error) {
555                                 sce->state &= ~UGEN_ASLP;
556                                 break;
557                         }
558                 }
559                 splx(s);
560
561                 /* Transfer as many chunks as possible. */
562                 while (sce->q.c_cc > 0 && uio->uio_resid > 0 && !error) {
563                         n = min(sce->q.c_cc, uio->uio_resid);
564                         if (n > sizeof(buffer))
565                                 n = sizeof(buffer);
566
567                         /* Remove a small chunk from the input queue. */
568                         q_to_b(&sce->q, buffer, n);
569                         DPRINTFN(5, ("ugenread: got %d chars\n", n));
570
571                         /* Copy the data to the user process. */
572                         error = uiomove(buffer, n, uio);
573                         if (error)
574                                 break;
575                 }
576                 break;
577         case UE_BULK:
578                 xfer = usbd_alloc_xfer(sc->sc_udev);
579                 if (xfer == 0)
580                         return (ENOMEM);
581                 while ((n = min(UGEN_BBSIZE, uio->uio_resid)) != 0) {
582                         DPRINTFN(1, ("ugenread: start transfer %d bytes\n",n));
583                         tn = n;
584                         err = usbd_bulk_transfer(
585                                 xfer, sce->pipeh,
586                                 sce->state & UGEN_SHORT_OK ? 
587                                     USBD_SHORT_XFER_OK : 0, 
588                                 sce->timeout, buf, &tn, "ugenrb");
589                         if (err) {
590                                 if (err == USBD_INTERRUPTED)
591                                         error = EINTR;
592                                 else if (err == USBD_TIMEOUT)
593                                         error = ETIMEDOUT;
594                                 else
595                                         error = EIO;
596                                 break;
597                         }
598                         DPRINTFN(1, ("ugenread: got %d bytes\n", tn));
599                         error = uiomove(buf, tn, uio);
600                         if (error || tn < n)
601                                 break;
602                 }
603                 usbd_free_xfer(xfer);
604                 break;
605         case UE_ISOCHRONOUS:
606                 s = splusb();
607                 while (sce->cur == sce->fill) {
608                         if (flag & IO_NDELAY) {
609                                 splx(s);
610                                 return (EWOULDBLOCK);
611                         }
612                         sce->state |= UGEN_ASLP;
613                         DPRINTFN(5, ("ugenread: sleep on %p\n", sc));
614                         error = tsleep(sce, PZERO | PCATCH, "ugenri", 0);
615                         DPRINTFN(5, ("ugenread: woke, error=%d\n", error));
616                         if (sc->sc_dying)
617                                 error = EIO;
618                         if (error) {
619                                 sce->state &= ~UGEN_ASLP;
620                                 break;
621                         }
622                 }
623
624                 while (sce->cur != sce->fill && uio->uio_resid > 0 && !error) {
625                         if(sce->fill > sce->cur)
626                                 n = min(sce->fill - sce->cur, uio->uio_resid);
627                         else
628                                 n = min(sce->limit - sce->cur, uio->uio_resid);
629
630                         DPRINTFN(5, ("ugenread: isoc got %d chars\n", n));
631
632                         /* Copy the data to the user process. */
633                         error = uiomove(sce->cur, n, uio);
634                         if (error)
635                                 break;
636                         sce->cur += n;
637                         if(sce->cur >= sce->limit)
638                                 sce->cur = sce->ibuf;
639                 }
640                 splx(s);
641                 break;
642
643                 
644         default:
645                 return (ENXIO);
646         }
647         return (error);
648 }
649
650 int
651 ugenread(dev_t dev, struct uio *uio, int flag)
652 {
653         int endpt = UGENENDPOINT(dev);
654         struct ugen_softc *sc;
655         int error;
656
657         USB_GET_SC(ugen, UGENUNIT(dev), sc);
658
659         sc->sc_refcnt++;
660         error = ugen_do_read(sc, endpt, uio, flag);
661         if (--sc->sc_refcnt < 0)
662                 usb_detach_wakeup(USBDEV(sc->sc_dev));
663         return (error);
664 }
665
666 Static int
667 ugen_do_write(struct ugen_softc *sc, int endpt, struct uio *uio, int flag)
668 {
669         struct ugen_endpoint *sce = &sc->sc_endpoints[endpt][OUT];
670         u_int32_t n;
671         int error = 0;
672         char buf[UGEN_BBSIZE];
673         usbd_xfer_handle xfer;
674         usbd_status err;
675
676         DPRINTFN(5, ("%s: ugen_do_write: %d\n", USBDEVNAME(sc->sc_dev), endpt));
677
678         if (sc->sc_dying)
679                 return (EIO);
680
681         if (endpt == USB_CONTROL_ENDPOINT)
682                 return (ENODEV);
683
684 #ifdef DIAGNOSTIC
685         if (sce->edesc == NULL) {
686                 printf("ugen_do_write: no edesc\n");
687                 return (EIO);
688         }
689         if (sce->pipeh == NULL) {
690                 printf("ugen_do_write: no pipe\n");
691                 return (EIO);
692         }
693 #endif
694
695         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
696         case UE_BULK:
697                 xfer = usbd_alloc_xfer(sc->sc_udev);
698                 if (xfer == 0)
699                         return (EIO);
700                 while ((n = min(UGEN_BBSIZE, uio->uio_resid)) != 0) {
701                         error = uiomove(buf, n, uio);
702                         if (error)
703                                 break;
704                         DPRINTFN(1, ("ugen_do_write: transfer %d bytes\n", n));
705                         err = usbd_bulk_transfer(xfer, sce->pipeh, 0, 
706                                   sce->timeout, buf, &n,"ugenwb");
707                         if (err) {
708                                 if (err == USBD_INTERRUPTED)
709                                         error = EINTR;
710                                 else
711                                         error = EIO;
712                                 break;
713                         }
714                 }
715                 usbd_free_xfer(xfer);
716                 break;
717         default:
718                 return (ENXIO);
719         }
720         return (error);
721 }
722
723 int
724 ugenwrite(dev_t dev, struct uio *uio, int flag)
725 {
726         int endpt = UGENENDPOINT(dev);
727         struct ugen_softc *sc;
728         int error;
729
730         USB_GET_SC(ugen, UGENUNIT(dev), sc);
731
732         sc->sc_refcnt++;
733         error = ugen_do_write(sc, endpt, uio, flag);
734         if (--sc->sc_refcnt < 0)
735                 usb_detach_wakeup(USBDEV(sc->sc_dev));
736         return (error);
737 }
738
739 #if defined(__NetBSD__) || defined(__OpenBSD__)
740 int
741 ugen_activate(device_ptr_t self, enum devact act)
742 {
743         struct ugen_softc *sc = (struct ugen_softc *)self;
744
745         switch (act) {
746         case DVACT_ACTIVATE:
747                 return (EOPNOTSUPP);
748                 break;
749
750         case DVACT_DEACTIVATE:
751                 sc->sc_dying = 1;
752                 break;
753         }
754         return (0);
755 }
756 #endif
757
758 USB_DETACH(ugen)
759 {
760         USB_DETACH_START(ugen, sc);
761         struct ugen_endpoint *sce;
762         int i, dir;
763         int s;
764 #if defined(__NetBSD__) || defined(__OpenBSD__)
765         int maj, mn;
766 #elif defined(__FreeBSD__)
767         int endptno;
768         dev_t dev;
769         struct vnode *vp;
770 #endif
771
772 #if defined(__NetBSD__) || defined(__OpenBSD__)
773         DPRINTF(("ugen_detach: sc=%p flags=%d\n", sc, flags));
774 #elif defined(__FreeBSD__)
775         DPRINTF(("ugen_detach: sc=%p\n", sc));
776 #endif
777
778         sc->sc_dying = 1;
779         /* Abort all pipes.  Causes processes waiting for transfer to wake. */
780         for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
781                 for (dir = OUT; dir <= IN; dir++) {
782                         sce = &sc->sc_endpoints[i][dir];
783                         if (sce && sce->pipeh)
784                                 usbd_abort_pipe(sce->pipeh);
785                 }
786         }
787
788         s = splusb();
789         if (--sc->sc_refcnt >= 0) {
790                 /* Wake everyone */
791                 for (i = 0; i < USB_MAX_ENDPOINTS; i++)
792                         wakeup(&sc->sc_endpoints[i][IN]);
793                 /* Wait for processes to go away. */
794                 usb_detach_wait(USBDEV(sc->sc_dev));
795         }
796         splx(s);
797
798 #if defined(__NetBSD__) || defined(__OpenBSD__)
799         /* locate the major number */
800         for (maj = 0; maj < nchrdev; maj++)
801                 if (cdevsw[maj].d_open == ugenopen)
802                         break;
803
804         /* Nuke the vnodes for any open instances (calls close). */
805         mn = self->dv_unit * USB_MAX_ENDPOINTS;
806         vdevgone(maj, mn, mn + USB_MAX_ENDPOINTS - 1, VCHR);
807 #elif defined(__FreeBSD__)
808         /* destroy the device for the control endpoint */
809         dev = makedev(UGEN_CDEV_MAJOR, UGENMINOR(USBDEVUNIT(sc->sc_dev), 0));
810         vp = SLIST_FIRST(&dev->si_hlist);
811         if (vp)
812                 VOP_REVOKE(vp, REVOKEALL);
813         destroy_dev(dev);
814
815         /* destroy all devices for the other (existing) endpoints as well */
816         for (endptno = 1; endptno < USB_MAX_ENDPOINTS; endptno++) {
817                 if (sc->sc_endpoints[endptno][IN].sc != NULL ||
818                     sc->sc_endpoints[endptno][OUT].sc != NULL ) {
819                         /* endpt can be 0x81 and 0x01, representing
820                          * endpoint address 0x01 and IN/OUT directions.
821                          * We map both endpoint addresses to the same device,
822                          * IN is reading from it, OUT is writing to it.
823                          *
824                          * In the if clause above we check whether one
825                          * of the structs is populated.
826                          */
827                         dev = makedev(UGEN_CDEV_MAJOR,
828                                 UGENMINOR(USBDEVUNIT(sc->sc_dev), endptno));
829                         vp = SLIST_FIRST(&dev->si_hlist);
830                         if (vp)
831                                 VOP_REVOKE(vp, REVOKEALL);
832
833                         destroy_dev(dev);
834                 }
835         }
836 #endif
837
838         return (0);
839 }
840
841 Static void
842 ugenintr(usbd_xfer_handle xfer, usbd_private_handle addr, usbd_status status)
843 {
844         struct ugen_endpoint *sce = addr;
845         /*struct ugen_softc *sc = sce->sc;*/
846         u_int32_t count;
847         u_char *ibuf;
848
849         if (status == USBD_CANCELLED)
850                 return;
851
852         if (status != USBD_NORMAL_COMPLETION) {
853                 DPRINTF(("ugenintr: status=%d\n", status));
854                 usbd_clear_endpoint_stall_async(sce->pipeh);
855                 return;
856         }
857
858         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
859         ibuf = sce->ibuf;
860
861         DPRINTFN(5, ("ugenintr: xfer=%p status=%d count=%d\n", 
862                      xfer, status, count));
863         DPRINTFN(5, ("          data = %02x %02x %02x\n",
864                      ibuf[0], ibuf[1], ibuf[2]));
865
866         (void)b_to_q(ibuf, count, &sce->q);
867                 
868         if (sce->state & UGEN_ASLP) {
869                 sce->state &= ~UGEN_ASLP;
870                 DPRINTFN(5, ("ugen_intr: waking %p\n", sce));
871                 wakeup(sce);
872         }
873         selwakeup(&sce->rsel);
874 }
875
876 Static void
877 ugen_isoc_rintr(usbd_xfer_handle xfer, usbd_private_handle addr, 
878                 usbd_status status)
879 {
880         struct isoreq *req = addr;
881         struct ugen_endpoint *sce = req->sce;
882         u_int32_t count, n;
883
884         /* Return if we are aborting. */
885         if (status == USBD_CANCELLED)
886                 return;
887
888         usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
889         DPRINTFN(5,("ugen_isoc_rintr: xfer %d, count=%d\n", req - sce->isoreqs,
890                     count));
891
892         /* throw away oldest input if the buffer is full */
893         if(sce->fill < sce->cur && sce->cur <= sce->fill + count) {
894                 sce->cur += count;
895                 if(sce->cur >= sce->limit)
896                         sce->cur = sce->ibuf + (sce->limit - sce->cur);
897                 DPRINTFN(5, ("ugen_isoc_rintr: throwing away %d bytes\n",
898                              count));
899         }
900
901         /* copy data to buffer */
902         while (count > 0) {
903                 n = min(count, sce->limit - sce->fill);
904                 memcpy(sce->fill, req->dmabuf, n);
905
906                 count -= n;
907                 sce->fill += n;
908                 if(sce->fill == sce->limit)
909                         sce->fill = sce->ibuf;
910         }
911
912         usbd_setup_isoc_xfer(xfer, sce->pipeh, req, req->sizes, UGEN_NISORFRMS,
913                              USBD_NO_COPY, ugen_isoc_rintr);
914         (void)usbd_transfer(xfer);
915
916         if (sce->state & UGEN_ASLP) {
917                 sce->state &= ~UGEN_ASLP;
918                 DPRINTFN(5, ("ugen_isoc_rintr: waking %p\n", sce));
919                 wakeup(sce);
920         }
921         selwakeup(&sce->rsel);
922 }
923
924 Static usbd_status
925 ugen_set_interface(struct ugen_softc *sc, int ifaceidx, int altno)
926 {
927         usbd_interface_handle iface;
928         usb_endpoint_descriptor_t *ed;
929         usbd_status err;
930         struct ugen_endpoint *sce;
931         u_int8_t niface, nendpt, endptno, endpt;
932         int dir;
933
934         DPRINTFN(15, ("ugen_set_interface %d %d\n", ifaceidx, altno));
935
936         err = usbd_interface_count(sc->sc_udev, &niface);
937         if (err)
938                 return (err);
939         if (ifaceidx < 0 || ifaceidx >= niface)
940                 return (USBD_INVAL);
941         
942         err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
943         if (err)
944                 return (err);
945         err = usbd_endpoint_count(iface, &nendpt);
946         if (err)
947                 return (err);
948         for (endptno = 0; endptno < nendpt; endptno++) {
949                 ed = usbd_interface2endpoint_descriptor(iface,endptno);
950                 endpt = ed->bEndpointAddress;
951                 dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
952                 sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
953                 sce->sc = 0;
954                 sce->edesc = 0;
955                 sce->iface = 0;
956         }
957
958         /* change setting */
959         err = usbd_set_interface(iface, altno);
960         if (err)
961                 return (err);
962
963         err = usbd_endpoint_count(iface, &nendpt);
964         if (err)
965                 return (err);
966         for (endptno = 0; endptno < nendpt; endptno++) {
967                 ed = usbd_interface2endpoint_descriptor(iface,endptno);
968                 endpt = ed->bEndpointAddress;
969                 dir = UE_GET_DIR(endpt) == UE_DIR_IN ? IN : OUT;
970                 sce = &sc->sc_endpoints[UE_GET_ADDR(endpt)][dir];
971                 sce->sc = sc;
972                 sce->edesc = ed;
973                 sce->iface = iface;
974         }
975         return (0);
976 }
977
978 /* Retrieve a complete descriptor for a certain device and index. */
979 Static usb_config_descriptor_t *
980 ugen_get_cdesc(struct ugen_softc *sc, int index, int *lenp)
981 {
982         usb_config_descriptor_t *cdesc, *tdesc, cdescr;
983         int len;
984         usbd_status err;
985
986         if (index == USB_CURRENT_CONFIG_INDEX) {
987                 tdesc = usbd_get_config_descriptor(sc->sc_udev);
988                 len = UGETW(tdesc->wTotalLength);
989                 if (lenp)
990                         *lenp = len;
991                 cdesc = malloc(len, M_TEMP, M_WAITOK);
992                 memcpy(cdesc, tdesc, len);
993                 DPRINTFN(5,("ugen_get_cdesc: current, len=%d\n", len));
994         } else {
995                 err = usbd_get_config_desc(sc->sc_udev, index, &cdescr);
996                 if (err)
997                         return (0);
998                 len = UGETW(cdescr.wTotalLength);
999                 DPRINTFN(5,("ugen_get_cdesc: index=%d, len=%d\n", index, len));
1000                 if (lenp)
1001                         *lenp = len;
1002                 cdesc = malloc(len, M_TEMP, M_WAITOK);
1003                 err = usbd_get_config_desc_full(sc->sc_udev, index, cdesc, len);
1004                 if (err) {
1005                         free(cdesc, M_TEMP);
1006                         return (0);
1007                 }
1008         }
1009         return (cdesc);
1010 }
1011
1012 Static int
1013 ugen_get_alt_index(struct ugen_softc *sc, int ifaceidx)
1014 {
1015         usbd_interface_handle iface;
1016         usbd_status err;
1017
1018         err = usbd_device2interface_handle(sc->sc_udev, ifaceidx, &iface);
1019         if (err)
1020                         return (-1);
1021         return (usbd_get_interface_altindex(iface));
1022 }
1023
1024 Static int
1025 ugen_do_ioctl(struct ugen_softc *sc, int endpt, u_long cmd,
1026               caddr_t addr, int flag, usb_proc_ptr p)
1027 {
1028         struct ugen_endpoint *sce;
1029         usbd_status err;
1030         usbd_interface_handle iface;
1031         struct usb_config_desc *cd;
1032         usb_config_descriptor_t *cdesc;
1033         struct usb_interface_desc *id;
1034         usb_interface_descriptor_t *idesc;
1035         struct usb_endpoint_desc *ed;
1036         usb_endpoint_descriptor_t *edesc;
1037         struct usb_alt_interface *ai;
1038         struct usb_string_desc *si;
1039         u_int8_t conf, alt;
1040
1041         DPRINTFN(5, ("ugenioctl: cmd=%08lx\n", cmd));
1042         if (sc->sc_dying)
1043                 return (EIO);
1044
1045         switch (cmd) {
1046         case FIONBIO:
1047                 /* All handled in the upper FS layer. */
1048                 return (0);
1049         case USB_SET_SHORT_XFER:
1050                 /* This flag only affects read */
1051                 if (endpt == USB_CONTROL_ENDPOINT)
1052                         return (EINVAL);
1053                 sce = &sc->sc_endpoints[endpt][IN];
1054                 if (sce == NULL)
1055                         return (EINVAL);
1056 #ifdef DIAGNOSTIC
1057                 if (sce->pipeh == NULL) {
1058                         printf("ugenioctl: USB_SET_SHORT_XFER, no pipe\n");
1059                         return (EIO);
1060                 }
1061 #endif
1062                 if (*(int *)addr)
1063                         sce->state |= UGEN_SHORT_OK;
1064                 else
1065                         sce->state &= ~UGEN_SHORT_OK;
1066                 return (0);
1067         case USB_SET_TIMEOUT:
1068                 sce = &sc->sc_endpoints[endpt][IN];
1069                 if (sce == NULL)
1070                         return (EINVAL);
1071 #ifdef DIAGNOSTIC
1072                 if (sce->pipeh == NULL) {
1073                         printf("ugenioctl: USB_SET_TIMEOUT, no pipe\n");
1074                         return (EIO);
1075                 }
1076 #endif
1077                 sce->timeout = *(int *)addr;
1078                 return (0);
1079         default:
1080                 break;
1081         }
1082
1083         if (endpt != USB_CONTROL_ENDPOINT)
1084                 return (EINVAL);
1085
1086         switch (cmd) {
1087 #ifdef USB_DEBUG
1088         case USB_SETDEBUG:
1089                 ugendebug = *(int *)addr;
1090                 break;
1091 #endif
1092         case USB_GET_CONFIG:
1093                 err = usbd_get_config(sc->sc_udev, &conf);
1094                 if (err)
1095                         return (EIO);
1096                 *(int *)addr = conf;
1097                 break;
1098         case USB_SET_CONFIG:
1099                 if (!(flag & FWRITE))
1100                         return (EPERM);
1101                 err = ugen_set_config(sc, *(int *)addr);
1102                 switch (err) {
1103                 case USBD_NORMAL_COMPLETION:
1104                         break;
1105                 case USBD_IN_USE:
1106                         return (EBUSY);
1107                 default:
1108                         return (EIO);
1109                 }
1110                 break;
1111         case USB_GET_ALTINTERFACE:
1112                 ai = (struct usb_alt_interface *)addr;
1113                 err = usbd_device2interface_handle(sc->sc_udev, 
1114                           ai->uai_interface_index, &iface);
1115                 if (err)
1116                         return (EINVAL);
1117                 idesc = usbd_get_interface_descriptor(iface);
1118                 if (idesc == NULL)
1119                         return (EIO);
1120                 ai->uai_alt_no = idesc->bAlternateSetting;
1121                 break;
1122         case USB_SET_ALTINTERFACE:
1123                 if (!(flag & FWRITE))
1124                         return (EPERM);
1125                 ai = (struct usb_alt_interface *)addr;
1126                 err = usbd_device2interface_handle(sc->sc_udev, 
1127                           ai->uai_interface_index, &iface);
1128                 if (err)
1129                         return (EINVAL);
1130                 err = ugen_set_interface(sc, ai->uai_interface_index, ai->uai_alt_no);
1131                 if (err)
1132                         return (EINVAL);
1133                 break;
1134         case USB_GET_NO_ALT:
1135                 ai = (struct usb_alt_interface *)addr;
1136                 cdesc = ugen_get_cdesc(sc, ai->uai_config_index, 0);
1137                 if (cdesc == NULL)
1138                         return (EINVAL);
1139                 idesc = usbd_find_idesc(cdesc, ai->uai_interface_index, 0);
1140                 if (idesc == NULL) {
1141                         free(cdesc, M_TEMP);
1142                         return (EINVAL);
1143                 }
1144                 ai->uai_alt_no = usbd_get_no_alts(cdesc, idesc->bInterfaceNumber);
1145                 free(cdesc, M_TEMP);
1146                 break;
1147         case USB_GET_DEVICE_DESC:
1148                 *(usb_device_descriptor_t *)addr =
1149                         *usbd_get_device_descriptor(sc->sc_udev);
1150                 break;
1151         case USB_GET_CONFIG_DESC:
1152                 cd = (struct usb_config_desc *)addr;
1153                 cdesc = ugen_get_cdesc(sc, cd->ucd_config_index, 0);
1154                 if (cdesc == NULL)
1155                         return (EINVAL);
1156                 cd->ucd_desc = *cdesc;
1157                 free(cdesc, M_TEMP);
1158                 break;
1159         case USB_GET_INTERFACE_DESC:
1160                 id = (struct usb_interface_desc *)addr;
1161                 cdesc = ugen_get_cdesc(sc, id->uid_config_index, 0);
1162                 if (cdesc == NULL)
1163                         return (EINVAL);
1164                 if (id->uid_config_index == USB_CURRENT_CONFIG_INDEX &&
1165                     id->uid_alt_index == USB_CURRENT_ALT_INDEX)
1166                         alt = ugen_get_alt_index(sc, id->uid_interface_index);
1167                 else
1168                         alt = id->uid_alt_index;
1169                 idesc = usbd_find_idesc(cdesc, id->uid_interface_index, alt);
1170                 if (idesc == NULL) {
1171                         free(cdesc, M_TEMP);
1172                         return (EINVAL);
1173                 }
1174                 id->uid_desc = *idesc;
1175                 free(cdesc, M_TEMP);
1176                 break;
1177         case USB_GET_ENDPOINT_DESC:
1178                 ed = (struct usb_endpoint_desc *)addr;
1179                 cdesc = ugen_get_cdesc(sc, ed->ued_config_index, 0);
1180                 if (cdesc == NULL)
1181                         return (EINVAL);
1182                 if (ed->ued_config_index == USB_CURRENT_CONFIG_INDEX &&
1183                     ed->ued_alt_index == USB_CURRENT_ALT_INDEX)
1184                         alt = ugen_get_alt_index(sc, ed->ued_interface_index);
1185                 else
1186                         alt = ed->ued_alt_index;
1187                 edesc = usbd_find_edesc(cdesc, ed->ued_interface_index, 
1188                                         alt, ed->ued_endpoint_index);
1189                 if (edesc == NULL) {
1190                         free(cdesc, M_TEMP);
1191                         return (EINVAL);
1192                 }
1193                 ed->ued_desc = *edesc;
1194                 free(cdesc, M_TEMP);
1195                 break;
1196         case USB_GET_FULL_DESC:
1197         {
1198                 int len;
1199                 struct iovec iov;
1200                 struct uio uio;
1201                 struct usb_full_desc *fd = (struct usb_full_desc *)addr;
1202                 int error;
1203
1204                 cdesc = ugen_get_cdesc(sc, fd->ufd_config_index, &len);
1205                 if (len > fd->ufd_size)
1206                         len = fd->ufd_size;
1207                 iov.iov_base = (caddr_t)fd->ufd_data;
1208                 iov.iov_len = len;
1209                 uio.uio_iov = &iov;
1210                 uio.uio_iovcnt = 1;
1211                 uio.uio_resid = len;
1212                 uio.uio_offset = 0;
1213                 uio.uio_segflg = UIO_USERSPACE;
1214                 uio.uio_rw = UIO_READ;
1215                 uio.uio_procp = p;
1216 #if defined(__NetBSD__) || defined(__OpenBSD__)
1217                 error = uiomove((caddr_t)cdesc, len, &uio);
1218 #elif defined(__FreeBSD__)
1219                 error = uiomove((void *)cdesc, len, &uio);
1220 #endif
1221                 free(cdesc, M_TEMP);
1222                 return (error);
1223         }
1224         case USB_GET_STRING_DESC:
1225                 si = (struct usb_string_desc *)addr;
1226                 err = usbd_get_string_desc(sc->sc_udev, si->usd_string_index, 
1227                           si->usd_language_id, &si->usd_desc);
1228                 if (err)
1229                         return (EINVAL);
1230                 break;
1231         case USB_DO_REQUEST:
1232         {
1233                 struct usb_ctl_request *ur = (void *)addr;
1234                 int len = UGETW(ur->ucr_request.wLength);
1235                 struct iovec iov;
1236                 struct uio uio;
1237                 void *ptr = 0;
1238                 usbd_status err;
1239                 int error = 0;
1240
1241                 if (!(flag & FWRITE))
1242                         return (EPERM);
1243                 /* Avoid requests that would damage the bus integrity. */
1244                 if ((ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1245                      ur->ucr_request.bRequest == UR_SET_ADDRESS) ||
1246                     (ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
1247                      ur->ucr_request.bRequest == UR_SET_CONFIG) ||
1248                     (ur->ucr_request.bmRequestType == UT_WRITE_INTERFACE &&
1249                      ur->ucr_request.bRequest == UR_SET_INTERFACE))
1250                         return (EINVAL);
1251
1252                 if (len < 0 || len > 32767)
1253                         return (EINVAL);
1254                 if (len != 0) {
1255                         iov.iov_base = (caddr_t)ur->ucr_data;
1256                         iov.iov_len = len;
1257                         uio.uio_iov = &iov;
1258                         uio.uio_iovcnt = 1;
1259                         uio.uio_resid = len;
1260                         uio.uio_offset = 0;
1261                         uio.uio_segflg = UIO_USERSPACE;
1262                         uio.uio_rw =
1263                                 ur->ucr_request.bmRequestType & UT_READ ? 
1264                                 UIO_READ : UIO_WRITE;
1265                         uio.uio_procp = p;
1266                         ptr = malloc(len, M_TEMP, M_WAITOK);
1267                         if (uio.uio_rw == UIO_WRITE) {
1268                                 error = uiomove(ptr, len, &uio);
1269                                 if (error)
1270                                         goto ret;
1271                         }
1272                 }
1273                 err = usbd_do_request_flags(sc->sc_udev, &ur->ucr_request, 
1274                           ptr, ur->ucr_flags, &ur->ucr_actlen);
1275                 if (err) {
1276                         error = EIO;
1277                         goto ret;
1278                 }
1279                 if (len != 0) {
1280                         if (uio.uio_rw == UIO_READ) {
1281                                 error = uiomove(ptr, len, &uio);
1282                                 if (error)
1283                                         goto ret;
1284                         }
1285                 }
1286         ret:
1287                 if (ptr)
1288                         free(ptr, M_TEMP);
1289                 return (error);
1290         }
1291         case USB_GET_DEVICEINFO:
1292                 usbd_fill_deviceinfo(sc->sc_udev,
1293                     (struct usb_device_info *)addr);
1294                 break;
1295         default:
1296                 return (EINVAL);
1297         }
1298         return (0);
1299 }
1300
1301 int
1302 ugenioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, usb_proc_ptr p)
1303 {
1304         int endpt = UGENENDPOINT(dev);
1305         struct ugen_softc *sc;
1306         int error;
1307
1308         USB_GET_SC(ugen, UGENUNIT(dev), sc);
1309
1310         sc->sc_refcnt++;
1311         error = ugen_do_ioctl(sc, endpt, cmd, addr, flag, p);
1312         if (--sc->sc_refcnt < 0)
1313                 usb_detach_wakeup(USBDEV(sc->sc_dev));
1314         return (error);
1315 }
1316
1317 int
1318 ugenpoll(dev_t dev, int events, usb_proc_ptr p)
1319 {
1320         struct ugen_softc *sc;
1321         struct ugen_endpoint *sce;
1322         int revents = 0;
1323         int s;
1324
1325         USB_GET_SC(ugen, UGENUNIT(dev), sc);
1326
1327         if (sc->sc_dying)
1328                 return (EIO);
1329
1330         /* XXX always IN */
1331         sce = &sc->sc_endpoints[UGENENDPOINT(dev)][IN];
1332         if (sce == NULL)
1333                 return (EINVAL);
1334 #ifdef DIAGNOSTIC
1335         if (!sce->edesc) {
1336                 printf("ugenpoll: no edesc\n");
1337                 return (EIO);
1338         }
1339         if (!sce->pipeh) {
1340                 printf("ugenpoll: no pipe\n");
1341                 return (EIO);
1342         }
1343 #endif
1344         s = splusb();
1345         switch (sce->edesc->bmAttributes & UE_XFERTYPE) {
1346         case UE_INTERRUPT:
1347                 if (events & (POLLIN | POLLRDNORM)) {
1348                         if (sce->q.c_cc > 0)
1349                                 revents |= events & (POLLIN | POLLRDNORM);
1350                         else
1351                                 selrecord(p, &sce->rsel);
1352                 }
1353                 break;
1354         case UE_ISOCHRONOUS:
1355                 if (events & (POLLIN | POLLRDNORM)) {
1356                         if (sce->cur != sce->fill)
1357                                 revents |= events & (POLLIN | POLLRDNORM);
1358                         else
1359                                 selrecord(p, &sce->rsel);
1360                 }
1361                 break;
1362         case UE_BULK:
1363                 /* 
1364                  * We have no easy way of determining if a read will
1365                  * yield any data or a write will happen.
1366                  * Pretend they will.
1367                  */
1368                 revents |= events & 
1369                            (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM);
1370                 break;
1371         default:
1372                 break;
1373         }
1374         splx(s);
1375         return (revents);
1376 }
1377
1378 #if defined(__FreeBSD__)
1379 DRIVER_MODULE(ugen, uhub, ugen_driver, ugen_devclass, usbd_driver_load, 0);
1380 #endif