kernel tree reorganization stage 1: Major cvs repository work (not logged as
[dragonfly.git] / sys / dev / usbmisc / ulpt / ulpt.c
1 /*      $NetBSD: ulpt.c,v 1.29 1999/11/17 23:00:50 augustss Exp $       */
2 /*      $FreeBSD: src/sys/dev/usb/ulpt.c,v 1.26.2.13 2002/11/06 20:23:50 joe Exp $      */
3 /*      $DragonFly: src/sys/dev/usbmisc/ulpt/ulpt.c,v 1.5 2003/08/07 21:17:14 dillon Exp $      */
4
5 /*
6  * Copyright (c) 1998 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@augustsson.net) at
11  * Carlstedt Research & Technology.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *        This product includes software developed by the NetBSD
24  *        Foundation, Inc. and its contributors.
25  * 4. Neither the name of The NetBSD Foundation nor the names of its
26  *    contributors may be used to endorse or promote products derived
27  *    from this software without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 /*
43  * Printer Class spec: http://www.usb.org/developers/data/usbprn10.pdf
44  */
45
46 /* XXX Note in the manpage the ULPT_NOPRIME version of the printer */
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/proc.h>
51 #include <sys/kernel.h>
52 #if defined(__NetBSD__) || defined(__OpenBSD__)
53 #include <sys/device.h>
54 #include <sys/ioctl.h>
55 #elif defined(__FreeBSD__)
56 #include <sys/module.h>
57 #include <sys/bus.h>
58 #endif
59 #include <sys/uio.h>
60 #include <sys/conf.h>
61 #include <sys/vnode.h>
62 #include <sys/syslog.h>
63 #include <sys/sysctl.h>
64
65 #include <bus/usb/usb.h>
66 #include <bus/usb/usbdi.h>
67 #include <bus/usb/usbdi_util.h>
68
69 #define TIMEOUT         hz*16   /* wait up to 16 seconds for a ready */
70 #define STEP            hz/4
71
72 #define ULPT_BSIZE      16384
73
74 #ifdef USB_DEBUG
75 #define DPRINTF(x)      if (ulptdebug) logprintf x
76 #define DPRINTFN(n,x)   if (ulptdebug>(n)) logprintf x
77 int     ulptdebug = 0;
78 SYSCTL_NODE(_hw_usb, OID_AUTO, ulpt, CTLFLAG_RW, 0, "USB ulpt");
79 SYSCTL_INT(_hw_usb_ulpt, OID_AUTO, debug, CTLFLAG_RW,
80            &ulptdebug, 0, "ulpt debug level");
81 #else
82 #define DPRINTF(x)
83 #define DPRINTFN(n,x)
84 #endif
85
86 #define UR_GET_DEVICE_ID 0
87 #define UR_GET_PORT_STATUS 1
88 #define UR_SOFT_RESET 2
89
90 #define LPS_NERR                0x08    /* printer no error */
91 #define LPS_SELECT              0x10    /* printer selected */
92 #define LPS_NOPAPER             0x20    /* printer out of paper */
93 #define LPS_INVERT      (LPS_SELECT|LPS_NERR)
94 #define LPS_MASK        (LPS_SELECT|LPS_NERR|LPS_NOPAPER)
95
96 struct ulpt_softc {
97         USBBASEDEVICE sc_dev;
98         usbd_device_handle sc_udev;     /* device */
99         usbd_interface_handle sc_iface; /* interface */
100         int sc_ifaceno;
101         usbd_pipe_handle sc_bulkpipe;   /* bulk pipe */
102         int sc_bulk;
103
104         u_char sc_state;
105 #define ULPT_OPEN       0x01    /* device is open */
106 #define ULPT_OBUSY      0x02    /* printer is busy doing output */
107 #define ULPT_INIT       0x04    /* waiting to initialize for open */
108         u_char sc_flags;
109 #define ULPT_NOPRIME    0x40    /* don't prime on open */
110         u_char sc_laststatus;
111
112         int sc_refcnt;
113         u_char sc_dying;
114
115 #if defined(__FreeBSD__)
116         dev_t dev;
117         dev_t dev_noprime;
118 #endif
119 };
120
121 #if defined(__NetBSD__) || defined(__OpenBSD__)
122 cdev_decl(ulpt);
123 #elif defined(__FreeBSD__)
124 Static d_open_t ulptopen;
125 Static d_close_t ulptclose;
126 Static d_write_t ulptwrite;
127 Static d_ioctl_t ulptioctl;
128
129 #define ULPT_CDEV_MAJOR 113
130
131 Static struct cdevsw ulpt_cdevsw = {
132         /* name */      "ulpt",
133         /* maj */       ULPT_CDEV_MAJOR,
134         /* flags */     0,
135         /* port */      NULL,
136         /* autoq */     0,
137
138         /* open */      ulptopen,
139         /* close */     ulptclose,
140         /* read */      noread,
141         /* write */     ulptwrite,
142         /* ioctl */     ulptioctl,
143         /* poll */      nopoll,
144         /* mmap */      nommap,
145         /* strategy */  nostrategy,
146         /* dump */      nodump,
147         /* psize */     nopsize
148 };
149 #endif
150
151 void ulpt_disco(void *);
152
153 int ulpt_do_write(struct ulpt_softc *, struct uio *uio, int);
154 int ulpt_status(struct ulpt_softc *);
155 void ulpt_reset(struct ulpt_softc *);
156 int ulpt_statusmsg(u_char, struct ulpt_softc *);
157
158 void ieee1284_print_id(char *);
159
160 #define ULPTUNIT(s)     (minor(s) & 0x1f)
161 #define ULPTFLAGS(s)    (minor(s) & 0xe0)
162
163
164 USB_DECLARE_DRIVER(ulpt);
165
166 USB_MATCH(ulpt)
167 {
168         USB_MATCH_START(ulpt, uaa);
169         usb_interface_descriptor_t *id;
170         
171         DPRINTFN(10,("ulpt_match\n"));
172         if (uaa->iface == NULL)
173                 return (UMATCH_NONE);
174         id = usbd_get_interface_descriptor(uaa->iface);
175         if (id != NULL &&
176             id->bInterfaceClass == UICLASS_PRINTER &&
177             id->bInterfaceSubClass == UISUBCLASS_PRINTER &&
178             (id->bInterfaceProtocol == UIPROTO_PRINTER_UNI ||
179              id->bInterfaceProtocol == UIPROTO_PRINTER_BI))
180                 return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
181         return (UMATCH_NONE);
182 }
183
184 USB_ATTACH(ulpt)
185 {
186         USB_ATTACH_START(ulpt, sc, uaa);
187         usbd_device_handle dev = uaa->device;
188         usbd_interface_handle iface = uaa->iface;
189         usb_interface_descriptor_t *id = usbd_get_interface_descriptor(iface);
190         char devinfo[1024];
191         usb_endpoint_descriptor_t *ed;
192         usbd_status err;
193         
194         DPRINTFN(10,("ulpt_attach: sc=%p\n", sc));
195         usbd_devinfo(dev, 0, devinfo);
196         USB_ATTACH_SETUP;
197         printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
198                devinfo, id->bInterfaceClass, id->bInterfaceSubClass);
199
200         /* Figure out which endpoint is the bulk out endpoint. */
201         ed = usbd_interface2endpoint_descriptor(iface, 0);
202         if (ed == NULL)
203                 goto nobulk;
204         if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_OUT ||
205             (ed->bmAttributes & UE_XFERTYPE) != UE_BULK) {
206                 /* In case we are using a bidir protocol... */
207                 ed = usbd_interface2endpoint_descriptor(iface, 1);
208                 if (ed == NULL)
209                         goto nobulk;
210                 if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_OUT ||
211                     (ed->bmAttributes & UE_XFERTYPE) != UE_BULK)
212                         goto nobulk;
213         }
214         sc->sc_bulk = ed->bEndpointAddress;
215         DPRINTFN(10, ("ulpt_attach: bulk=%d\n", sc->sc_bulk));
216
217         sc->sc_iface = iface;
218         err = usbd_interface2device_handle(iface, &sc->sc_udev);
219         if (err) {
220                 sc->sc_dying = 1;
221                 USB_ATTACH_ERROR_RETURN;
222         }
223         sc->sc_ifaceno = id->bInterfaceNumber;
224
225 #if 0
226 /*
227  * This code is disabled because for some mysterious reason it causes
228  * printing not to work.  But only sometimes, and mostly with
229  * UHCI and less often with OHCI.  *sigh*
230  */
231         {
232         usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
233         usb_device_request_t req;
234         int len, alen;
235
236         req.bmRequestType = UT_READ_CLASS_INTERFACE;
237         req.bRequest = UR_GET_DEVICE_ID;
238         USETW(req.wValue, cd->bConfigurationValue);
239         USETW2(req.wIndex, id->bInterfaceNumber, id->bAlternateSetting);
240         USETW(req.wLength, sizeof devinfo - 1);
241         err = usbd_do_request_flags(dev, &req, devinfo, USBD_SHORT_XFER_OK,
242                   &alen);
243         if (err) {
244                 printf("%s: cannot get device id\n", USBDEVNAME(sc->sc_dev));
245         } else if (alen <= 2) {
246                 printf("%s: empty device id, no printer connected?\n",
247                        USBDEVNAME(sc->sc_dev));
248         } else {
249                 /* devinfo now contains an IEEE-1284 device ID */
250                 len = ((devinfo[0] & 0xff) << 8) | (devinfo[1] & 0xff);
251                 if (len > sizeof devinfo - 3)
252                         len = sizeof devinfo - 3;
253                 devinfo[len] = 0;
254                 printf("%s: device id <", USBDEVNAME(sc->sc_dev));
255                 ieee1284_print_id(devinfo+2);
256                 printf(">\n");
257         }
258         }
259 #endif
260
261 #if defined(__FreeBSD__)
262         sc->dev = make_dev(&ulpt_cdevsw, device_get_unit(self),
263                 UID_ROOT, GID_OPERATOR, 0644, "ulpt%d", device_get_unit(self));
264         sc->dev_noprime = make_dev(&ulpt_cdevsw,
265                 device_get_unit(self)|ULPT_NOPRIME,
266                 UID_ROOT, GID_OPERATOR, 0644, "unlpt%d", device_get_unit(self));
267 #endif
268
269         USB_ATTACH_SUCCESS_RETURN;
270
271  nobulk:
272         printf("%s: could not find bulk endpoint\n", USBDEVNAME(sc->sc_dev));
273         sc->sc_dying = 1;
274         USB_ATTACH_ERROR_RETURN;
275 }
276
277 #if defined(__NetBSD__) || defined(__OpenBSD__)
278 int
279 ulpt_activate(device_ptr_t self, enum devact act)
280 {
281         struct ulpt_softc *sc = (struct ulpt_softc *)self;
282
283         switch (act) {
284         case DVACT_ACTIVATE:
285                 return (EOPNOTSUPP);
286                 break;
287
288         case DVACT_DEACTIVATE:
289                 sc->sc_dying = 1;
290                 break;
291         }
292         return (0);
293 }
294 #endif
295
296 USB_DETACH(ulpt)
297 {
298         USB_DETACH_START(ulpt, sc);
299         int s;
300 #if defined(__NetBSD__) || defined(__OpenBSD__)
301         int maj, mn;
302 #elif defined(__FreeBSD__)
303         struct vnode *vp;
304 #endif
305
306 #if defined(__NetBSD__) || defined(__OpenBSD__)
307         DPRINTF(("ulpt_detach: sc=%p flags=%d\n", sc, flags));
308 #elif defined(__FreeBSD__)
309         DPRINTF(("ulpt_detach: sc=%p\n", sc));
310 #endif
311
312         sc->sc_dying = 1;
313         if (sc->sc_bulkpipe != NULL)
314                 usbd_abort_pipe(sc->sc_bulkpipe);
315
316         s = splusb();
317         if (--sc->sc_refcnt >= 0) {
318                 /* There is noone to wake, aborting the pipe is enough */
319                 /* Wait for processes to go away. */
320                 usb_detach_wait(USBDEV(sc->sc_dev));
321         }
322         splx(s);
323
324 #if defined(__NetBSD__) || defined(__OpenBSD__)
325         /* locate the major number */
326         for (maj = 0; maj < nchrdev; maj++)
327                 if (cdevsw[maj].d_open == ulptopen)
328                         break;
329
330         /* Nuke the vnodes for any open instances (calls close). */
331         mn = self->dv_unit;
332         vdevgone(maj, mn, mn, VCHR);
333 #elif defined(__FreeBSD__)
334         vp = SLIST_FIRST(&sc->dev->si_hlist);
335         if (vp)
336                 VOP_REVOKE(vp, REVOKEALL);
337         vp = SLIST_FIRST(&sc->dev_noprime->si_hlist);
338         if (vp)
339                 VOP_REVOKE(vp, REVOKEALL);
340
341         destroy_dev(sc->dev);
342         destroy_dev(sc->dev_noprime);
343 #endif
344
345         return (0);
346 }
347
348 int
349 ulpt_status(struct ulpt_softc *sc)
350 {
351         usb_device_request_t req;
352         usbd_status err;
353         u_char status;
354
355         req.bmRequestType = UT_READ_CLASS_INTERFACE;
356         req.bRequest = UR_GET_PORT_STATUS;
357         USETW(req.wValue, 0);
358         USETW(req.wIndex, sc->sc_ifaceno);
359         USETW(req.wLength, 1);
360         err = usbd_do_request(sc->sc_udev, &req, &status);
361         DPRINTFN(1, ("ulpt_status: status=0x%02x err=%d\n", status, err));
362         if (!err)
363                 return (status);
364         else
365                 return (0);
366 }
367
368 void
369 ulpt_reset(struct ulpt_softc *sc)
370 {
371         usb_device_request_t req;
372
373         DPRINTFN(1, ("ulpt_reset\n"));
374         req.bmRequestType = UT_WRITE_CLASS_OTHER;
375         req.bRequest = UR_SOFT_RESET;
376         USETW(req.wValue, 0);
377         USETW(req.wIndex, sc->sc_ifaceno);
378         USETW(req.wLength, 0);
379         (void)usbd_do_request(sc->sc_udev, &req, 0);
380 }
381
382 /*
383  * Reset the printer, then wait until it's selected and not busy.
384  */
385 int
386 ulptopen(dev_t dev, int flag, int mode, usb_proc_ptr p)
387 {
388         u_char flags = ULPTFLAGS(dev);
389         struct ulpt_softc *sc;
390         usbd_status err;
391         int spin, error;
392
393         USB_GET_SC_OPEN(ulpt, ULPTUNIT(dev), sc);
394
395         if (sc == NULL || sc->sc_iface == NULL || sc->sc_dying)
396                 return (ENXIO);
397
398         if (sc->sc_state)
399                 return (EBUSY);
400
401         sc->sc_state = ULPT_INIT;
402         sc->sc_flags = flags;
403         DPRINTF(("ulptopen: flags=0x%x\n", (unsigned)flags));
404
405 #if defined(USB_DEBUG) && defined(__FreeBSD__)
406         /* Ignoring these flags might not be a good idea */
407         if ((flags & ~ULPT_NOPRIME) != 0)
408                 printf("ulptopen: flags ignored: %b\n", flags,
409                         "\20\3POS_INIT\4POS_ACK\6PRIME_OPEN\7AUTOLF\10BYPASS");
410 #endif
411
412
413         if ((flags & ULPT_NOPRIME) == 0)
414                 ulpt_reset(sc);
415
416         for (spin = 0; (ulpt_status(sc) & LPS_SELECT) == 0; spin += STEP) {
417                 if (spin >= TIMEOUT) {
418                         sc->sc_state = 0;
419                         return (EBUSY);
420                 }
421
422                 /* wait 1/4 second, give up if we get a signal */
423                 error = tsleep((caddr_t)sc, PCATCH, "ulptop", STEP);
424                 if (error != EWOULDBLOCK) {
425                         sc->sc_state = 0;
426                         return (error);
427                 }
428
429                 if (sc->sc_dying) {
430                         sc->sc_state = 0;
431                         return (ENXIO);
432                 }
433         }
434
435         err = usbd_open_pipe(sc->sc_iface, sc->sc_bulk, 0, &sc->sc_bulkpipe);
436         if (err) {
437                 sc->sc_state = 0;
438                 return (EIO);
439         }
440
441         sc->sc_state = ULPT_OPEN;
442
443         DPRINTF(("ulptopen: done\n"));
444         return (0);
445 }
446
447 int
448 ulpt_statusmsg(u_char status, struct ulpt_softc *sc)
449 {
450         u_char new;
451
452         status = (status ^ LPS_INVERT) & LPS_MASK;
453         new = status & ~sc->sc_laststatus;
454         sc->sc_laststatus = status;
455
456         if (new & LPS_SELECT)
457                 log(LOG_NOTICE, "%s: offline\n", USBDEVNAME(sc->sc_dev));
458         else if (new & LPS_NOPAPER)
459                 log(LOG_NOTICE, "%s: out of paper\n", USBDEVNAME(sc->sc_dev));
460         else if (new & LPS_NERR)
461                 log(LOG_NOTICE, "%s: output error\n", USBDEVNAME(sc->sc_dev));
462
463         return (status);
464 }
465
466 int
467 ulptclose(dev_t dev, int flag, int mode, usb_proc_ptr p)
468 {
469         struct ulpt_softc *sc;
470
471         USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
472
473         if (sc->sc_state != ULPT_OPEN)
474                 /* We are being forced to close before the open completed. */
475                 return (0);
476
477         usbd_close_pipe(sc->sc_bulkpipe);
478         sc->sc_bulkpipe = 0;
479
480         sc->sc_state = 0;
481
482         DPRINTF(("ulptclose: closed\n"));
483         return (0);
484 }
485
486 int
487 ulpt_do_write(struct ulpt_softc *sc, struct uio *uio, int flags)
488 {
489         u_int32_t n;
490         int error = 0;
491         void *bufp;
492         usbd_xfer_handle xfer;
493         usbd_status err;
494
495         DPRINTF(("ulptwrite\n"));
496         xfer = usbd_alloc_xfer(sc->sc_udev);
497         if (xfer == NULL)
498                 return (ENOMEM);
499         bufp = usbd_alloc_buffer(xfer, ULPT_BSIZE);
500         if (bufp == NULL) {
501                 usbd_free_xfer(xfer);
502                 return (ENOMEM);
503         }
504         while ((n = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
505                 ulpt_statusmsg(ulpt_status(sc), sc);
506                 error = uiomove(bufp, n, uio);
507                 if (error)
508                         break;
509                 DPRINTFN(1, ("ulptwrite: transfer %d bytes\n", n));
510                 err = usbd_bulk_transfer(xfer, sc->sc_bulkpipe, USBD_NO_COPY, 
511                           USBD_NO_TIMEOUT, bufp, &n, "ulptwr");
512                 if (err) {
513                         DPRINTF(("ulptwrite: error=%d\n", err));
514                         error = EIO;
515                         break;
516                 }
517         }
518         usbd_free_xfer(xfer);
519
520         return (error);
521 }
522
523 int
524 ulptwrite(dev_t dev, struct uio *uio, int flags)
525 {
526         struct ulpt_softc *sc;
527         int error;
528
529         USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
530
531         if (sc->sc_dying)
532                 return (EIO);
533
534         sc->sc_refcnt++;
535         error = ulpt_do_write(sc, uio, flags);
536         if (--sc->sc_refcnt < 0)
537                 usb_detach_wakeup(USBDEV(sc->sc_dev));
538         return (error);
539 }
540
541 int
542 ulptioctl(dev_t dev, u_long cmd, caddr_t data, int flag, usb_proc_ptr p)
543 {
544         int error = 0;
545
546         switch (cmd) {
547         default:
548                 error = ENODEV;
549         }
550
551         return (error);
552 }
553
554 #if 0
555 /* XXX This does not belong here. */
556 /*
557  * Print select parts of a IEEE 1284 device ID.
558  */
559 void
560 ieee1284_print_id(char *str)
561 {
562         char *p, *q;
563
564         for (p = str-1; p; p = strchr(p, ';')) {
565                 p++;            /* skip ';' */
566                 if (strncmp(p, "MFG:", 4) == 0 ||
567                     strncmp(p, "MANUFACTURER:", 14) == 0 ||
568                     strncmp(p, "MDL:", 4) == 0 ||
569                     strncmp(p, "MODEL:", 6) == 0) {
570                         q = strchr(p, ';');
571                         if (q)
572                                 printf("%.*s", (int)(q - p + 1), p);
573                 }
574         }
575 }
576 #endif
577
578 #if defined(__FreeBSD__)
579 DRIVER_MODULE(ulpt, uhub, ulpt_driver, ulpt_devclass, usbd_driver_load, 0);
580 #endif