dfaf7c6e1e6682e160f7405f524987df3408f396
[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.2 2003/06/17 04:28:32 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 <dev/usb/usb.h>
66 #include <dev/usb/usbdi.h>
67 #include <dev/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 LPTPRI          (PZERO+8)
73 #define ULPT_BSIZE      16384
74
75 #ifdef USB_DEBUG
76 #define DPRINTF(x)      if (ulptdebug) logprintf x
77 #define DPRINTFN(n,x)   if (ulptdebug>(n)) logprintf x
78 int     ulptdebug = 0;
79 SYSCTL_NODE(_hw_usb, OID_AUTO, ulpt, CTLFLAG_RW, 0, "USB ulpt");
80 SYSCTL_INT(_hw_usb_ulpt, OID_AUTO, debug, CTLFLAG_RW,
81            &ulptdebug, 0, "ulpt debug level");
82 #else
83 #define DPRINTF(x)
84 #define DPRINTFN(n,x)
85 #endif
86
87 #define UR_GET_DEVICE_ID 0
88 #define UR_GET_PORT_STATUS 1
89 #define UR_SOFT_RESET 2
90
91 #define LPS_NERR                0x08    /* printer no error */
92 #define LPS_SELECT              0x10    /* printer selected */
93 #define LPS_NOPAPER             0x20    /* printer out of paper */
94 #define LPS_INVERT      (LPS_SELECT|LPS_NERR)
95 #define LPS_MASK        (LPS_SELECT|LPS_NERR|LPS_NOPAPER)
96
97 struct ulpt_softc {
98         USBBASEDEVICE sc_dev;
99         usbd_device_handle sc_udev;     /* device */
100         usbd_interface_handle sc_iface; /* interface */
101         int sc_ifaceno;
102         usbd_pipe_handle sc_bulkpipe;   /* bulk pipe */
103         int sc_bulk;
104
105         u_char sc_state;
106 #define ULPT_OPEN       0x01    /* device is open */
107 #define ULPT_OBUSY      0x02    /* printer is busy doing output */
108 #define ULPT_INIT       0x04    /* waiting to initialize for open */
109         u_char sc_flags;
110 #define ULPT_NOPRIME    0x40    /* don't prime on open */
111         u_char sc_laststatus;
112
113         int sc_refcnt;
114         u_char sc_dying;
115
116 #if defined(__FreeBSD__)
117         dev_t dev;
118         dev_t dev_noprime;
119 #endif
120 };
121
122 #if defined(__NetBSD__) || defined(__OpenBSD__)
123 cdev_decl(ulpt);
124 #elif defined(__FreeBSD__)
125 Static d_open_t ulptopen;
126 Static d_close_t ulptclose;
127 Static d_write_t ulptwrite;
128 Static d_ioctl_t ulptioctl;
129
130 #define ULPT_CDEV_MAJOR 113
131
132 Static struct cdevsw ulpt_cdevsw = {
133         /* open */      ulptopen,
134         /* close */     ulptclose,
135         /* read */      noread,
136         /* write */     ulptwrite,
137         /* ioctl */     ulptioctl,
138         /* poll */      nopoll,
139         /* mmap */      nommap,
140         /* strategy */  nostrategy,
141         /* name */      "ulpt",
142         /* maj */       ULPT_CDEV_MAJOR,
143         /* dump */      nodump,
144         /* psize */     nopsize,
145         /* flags */     0,
146         /* bmaj */      -1
147 };
148 #endif
149
150 void ulpt_disco(void *);
151
152 int ulpt_do_write(struct ulpt_softc *, struct uio *uio, int);
153 int ulpt_status(struct ulpt_softc *);
154 void ulpt_reset(struct ulpt_softc *);
155 int ulpt_statusmsg(u_char, struct ulpt_softc *);
156
157 void ieee1284_print_id(char *);
158
159 #define ULPTUNIT(s)     (minor(s) & 0x1f)
160 #define ULPTFLAGS(s)    (minor(s) & 0xe0)
161
162
163 USB_DECLARE_DRIVER(ulpt);
164
165 USB_MATCH(ulpt)
166 {
167         USB_MATCH_START(ulpt, uaa);
168         usb_interface_descriptor_t *id;
169         
170         DPRINTFN(10,("ulpt_match\n"));
171         if (uaa->iface == NULL)
172                 return (UMATCH_NONE);
173         id = usbd_get_interface_descriptor(uaa->iface);
174         if (id != NULL &&
175             id->bInterfaceClass == UICLASS_PRINTER &&
176             id->bInterfaceSubClass == UISUBCLASS_PRINTER &&
177             (id->bInterfaceProtocol == UIPROTO_PRINTER_UNI ||
178              id->bInterfaceProtocol == UIPROTO_PRINTER_BI))
179                 return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
180         return (UMATCH_NONE);
181 }
182
183 USB_ATTACH(ulpt)
184 {
185         USB_ATTACH_START(ulpt, sc, uaa);
186         usbd_device_handle dev = uaa->device;
187         usbd_interface_handle iface = uaa->iface;
188         usb_interface_descriptor_t *id = usbd_get_interface_descriptor(iface);
189         char devinfo[1024];
190         usb_endpoint_descriptor_t *ed;
191         usbd_status err;
192         
193         DPRINTFN(10,("ulpt_attach: sc=%p\n", sc));
194         usbd_devinfo(dev, 0, devinfo);
195         USB_ATTACH_SETUP;
196         printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
197                devinfo, id->bInterfaceClass, id->bInterfaceSubClass);
198
199         /* Figure out which endpoint is the bulk out endpoint. */
200         ed = usbd_interface2endpoint_descriptor(iface, 0);
201         if (ed == NULL)
202                 goto nobulk;
203         if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_OUT ||
204             (ed->bmAttributes & UE_XFERTYPE) != UE_BULK) {
205                 /* In case we are using a bidir protocol... */
206                 ed = usbd_interface2endpoint_descriptor(iface, 1);
207                 if (ed == NULL)
208                         goto nobulk;
209                 if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_OUT ||
210                     (ed->bmAttributes & UE_XFERTYPE) != UE_BULK)
211                         goto nobulk;
212         }
213         sc->sc_bulk = ed->bEndpointAddress;
214         DPRINTFN(10, ("ulpt_attach: bulk=%d\n", sc->sc_bulk));
215
216         sc->sc_iface = iface;
217         err = usbd_interface2device_handle(iface, &sc->sc_udev);
218         if (err) {
219                 sc->sc_dying = 1;
220                 USB_ATTACH_ERROR_RETURN;
221         }
222         sc->sc_ifaceno = id->bInterfaceNumber;
223
224 #if 0
225 /*
226  * This code is disabled because for some mysterious reason it causes
227  * printing not to work.  But only sometimes, and mostly with
228  * UHCI and less often with OHCI.  *sigh*
229  */
230         {
231         usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
232         usb_device_request_t req;
233         int len, alen;
234
235         req.bmRequestType = UT_READ_CLASS_INTERFACE;
236         req.bRequest = UR_GET_DEVICE_ID;
237         USETW(req.wValue, cd->bConfigurationValue);
238         USETW2(req.wIndex, id->bInterfaceNumber, id->bAlternateSetting);
239         USETW(req.wLength, sizeof devinfo - 1);
240         err = usbd_do_request_flags(dev, &req, devinfo, USBD_SHORT_XFER_OK,
241                   &alen);
242         if (err) {
243                 printf("%s: cannot get device id\n", USBDEVNAME(sc->sc_dev));
244         } else if (alen <= 2) {
245                 printf("%s: empty device id, no printer connected?\n",
246                        USBDEVNAME(sc->sc_dev));
247         } else {
248                 /* devinfo now contains an IEEE-1284 device ID */
249                 len = ((devinfo[0] & 0xff) << 8) | (devinfo[1] & 0xff);
250                 if (len > sizeof devinfo - 3)
251                         len = sizeof devinfo - 3;
252                 devinfo[len] = 0;
253                 printf("%s: device id <", USBDEVNAME(sc->sc_dev));
254                 ieee1284_print_id(devinfo+2);
255                 printf(">\n");
256         }
257         }
258 #endif
259
260 #if defined(__FreeBSD__)
261         sc->dev = make_dev(&ulpt_cdevsw, device_get_unit(self),
262                 UID_ROOT, GID_OPERATOR, 0644, "ulpt%d", device_get_unit(self));
263         sc->dev_noprime = make_dev(&ulpt_cdevsw,
264                 device_get_unit(self)|ULPT_NOPRIME,
265                 UID_ROOT, GID_OPERATOR, 0644, "unlpt%d", device_get_unit(self));
266 #endif
267
268         USB_ATTACH_SUCCESS_RETURN;
269
270  nobulk:
271         printf("%s: could not find bulk endpoint\n", USBDEVNAME(sc->sc_dev));
272         sc->sc_dying = 1;
273         USB_ATTACH_ERROR_RETURN;
274 }
275
276 #if defined(__NetBSD__) || defined(__OpenBSD__)
277 int
278 ulpt_activate(device_ptr_t self, enum devact act)
279 {
280         struct ulpt_softc *sc = (struct ulpt_softc *)self;
281
282         switch (act) {
283         case DVACT_ACTIVATE:
284                 return (EOPNOTSUPP);
285                 break;
286
287         case DVACT_DEACTIVATE:
288                 sc->sc_dying = 1;
289                 break;
290         }
291         return (0);
292 }
293 #endif
294
295 USB_DETACH(ulpt)
296 {
297         USB_DETACH_START(ulpt, sc);
298         int s;
299 #if defined(__NetBSD__) || defined(__OpenBSD__)
300         int maj, mn;
301 #elif defined(__FreeBSD__)
302         struct vnode *vp;
303 #endif
304
305 #if defined(__NetBSD__) || defined(__OpenBSD__)
306         DPRINTF(("ulpt_detach: sc=%p flags=%d\n", sc, flags));
307 #elif defined(__FreeBSD__)
308         DPRINTF(("ulpt_detach: sc=%p\n", sc));
309 #endif
310
311         sc->sc_dying = 1;
312         if (sc->sc_bulkpipe != NULL)
313                 usbd_abort_pipe(sc->sc_bulkpipe);
314
315         s = splusb();
316         if (--sc->sc_refcnt >= 0) {
317                 /* There is noone to wake, aborting the pipe is enough */
318                 /* Wait for processes to go away. */
319                 usb_detach_wait(USBDEV(sc->sc_dev));
320         }
321         splx(s);
322
323 #if defined(__NetBSD__) || defined(__OpenBSD__)
324         /* locate the major number */
325         for (maj = 0; maj < nchrdev; maj++)
326                 if (cdevsw[maj].d_open == ulptopen)
327                         break;
328
329         /* Nuke the vnodes for any open instances (calls close). */
330         mn = self->dv_unit;
331         vdevgone(maj, mn, mn, VCHR);
332 #elif defined(__FreeBSD__)
333         vp = SLIST_FIRST(&sc->dev->si_hlist);
334         if (vp)
335                 VOP_REVOKE(vp, REVOKEALL);
336         vp = SLIST_FIRST(&sc->dev_noprime->si_hlist);
337         if (vp)
338                 VOP_REVOKE(vp, REVOKEALL);
339
340         destroy_dev(sc->dev);
341         destroy_dev(sc->dev_noprime);
342 #endif
343
344         return (0);
345 }
346
347 int
348 ulpt_status(struct ulpt_softc *sc)
349 {
350         usb_device_request_t req;
351         usbd_status err;
352         u_char status;
353
354         req.bmRequestType = UT_READ_CLASS_INTERFACE;
355         req.bRequest = UR_GET_PORT_STATUS;
356         USETW(req.wValue, 0);
357         USETW(req.wIndex, sc->sc_ifaceno);
358         USETW(req.wLength, 1);
359         err = usbd_do_request(sc->sc_udev, &req, &status);
360         DPRINTFN(1, ("ulpt_status: status=0x%02x err=%d\n", status, err));
361         if (!err)
362                 return (status);
363         else
364                 return (0);
365 }
366
367 void
368 ulpt_reset(struct ulpt_softc *sc)
369 {
370         usb_device_request_t req;
371
372         DPRINTFN(1, ("ulpt_reset\n"));
373         req.bmRequestType = UT_WRITE_CLASS_OTHER;
374         req.bRequest = UR_SOFT_RESET;
375         USETW(req.wValue, 0);
376         USETW(req.wIndex, sc->sc_ifaceno);
377         USETW(req.wLength, 0);
378         (void)usbd_do_request(sc->sc_udev, &req, 0);
379 }
380
381 /*
382  * Reset the printer, then wait until it's selected and not busy.
383  */
384 int
385 ulptopen(dev_t dev, int flag, int mode, usb_proc_ptr p)
386 {
387         u_char flags = ULPTFLAGS(dev);
388         struct ulpt_softc *sc;
389         usbd_status err;
390         int spin, error;
391
392         USB_GET_SC_OPEN(ulpt, ULPTUNIT(dev), sc);
393
394         if (sc == NULL || sc->sc_iface == NULL || sc->sc_dying)
395                 return (ENXIO);
396
397         if (sc->sc_state)
398                 return (EBUSY);
399
400         sc->sc_state = ULPT_INIT;
401         sc->sc_flags = flags;
402         DPRINTF(("ulptopen: flags=0x%x\n", (unsigned)flags));
403
404 #if defined(USB_DEBUG) && defined(__FreeBSD__)
405         /* Ignoring these flags might not be a good idea */
406         if ((flags & ~ULPT_NOPRIME) != 0)
407                 printf("ulptopen: flags ignored: %b\n", flags,
408                         "\20\3POS_INIT\4POS_ACK\6PRIME_OPEN\7AUTOLF\10BYPASS");
409 #endif
410
411
412         if ((flags & ULPT_NOPRIME) == 0)
413                 ulpt_reset(sc);
414
415         for (spin = 0; (ulpt_status(sc) & LPS_SELECT) == 0; spin += STEP) {
416                 if (spin >= TIMEOUT) {
417                         sc->sc_state = 0;
418                         return (EBUSY);
419                 }
420
421                 /* wait 1/4 second, give up if we get a signal */
422                 error = tsleep((caddr_t)sc, LPTPRI | PCATCH, "ulptop", STEP);
423                 if (error != EWOULDBLOCK) {
424                         sc->sc_state = 0;
425                         return (error);
426                 }
427
428                 if (sc->sc_dying) {
429                         sc->sc_state = 0;
430                         return (ENXIO);
431                 }
432         }
433
434         err = usbd_open_pipe(sc->sc_iface, sc->sc_bulk, 0, &sc->sc_bulkpipe);
435         if (err) {
436                 sc->sc_state = 0;
437                 return (EIO);
438         }
439
440         sc->sc_state = ULPT_OPEN;
441
442         DPRINTF(("ulptopen: done\n"));
443         return (0);
444 }
445
446 int
447 ulpt_statusmsg(u_char status, struct ulpt_softc *sc)
448 {
449         u_char new;
450
451         status = (status ^ LPS_INVERT) & LPS_MASK;
452         new = status & ~sc->sc_laststatus;
453         sc->sc_laststatus = status;
454
455         if (new & LPS_SELECT)
456                 log(LOG_NOTICE, "%s: offline\n", USBDEVNAME(sc->sc_dev));
457         else if (new & LPS_NOPAPER)
458                 log(LOG_NOTICE, "%s: out of paper\n", USBDEVNAME(sc->sc_dev));
459         else if (new & LPS_NERR)
460                 log(LOG_NOTICE, "%s: output error\n", USBDEVNAME(sc->sc_dev));
461
462         return (status);
463 }
464
465 int
466 ulptclose(dev_t dev, int flag, int mode, usb_proc_ptr p)
467 {
468         struct ulpt_softc *sc;
469
470         USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
471
472         if (sc->sc_state != ULPT_OPEN)
473                 /* We are being forced to close before the open completed. */
474                 return (0);
475
476         usbd_close_pipe(sc->sc_bulkpipe);
477         sc->sc_bulkpipe = 0;
478
479         sc->sc_state = 0;
480
481         DPRINTF(("ulptclose: closed\n"));
482         return (0);
483 }
484
485 int
486 ulpt_do_write(struct ulpt_softc *sc, struct uio *uio, int flags)
487 {
488         u_int32_t n;
489         int error = 0;
490         void *bufp;
491         usbd_xfer_handle xfer;
492         usbd_status err;
493
494         DPRINTF(("ulptwrite\n"));
495         xfer = usbd_alloc_xfer(sc->sc_udev);
496         if (xfer == NULL)
497                 return (ENOMEM);
498         bufp = usbd_alloc_buffer(xfer, ULPT_BSIZE);
499         if (bufp == NULL) {
500                 usbd_free_xfer(xfer);
501                 return (ENOMEM);
502         }
503         while ((n = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
504                 ulpt_statusmsg(ulpt_status(sc), sc);
505                 error = uiomove(bufp, n, uio);
506                 if (error)
507                         break;
508                 DPRINTFN(1, ("ulptwrite: transfer %d bytes\n", n));
509                 err = usbd_bulk_transfer(xfer, sc->sc_bulkpipe, USBD_NO_COPY, 
510                           USBD_NO_TIMEOUT, bufp, &n, "ulptwr");
511                 if (err) {
512                         DPRINTF(("ulptwrite: error=%d\n", err));
513                         error = EIO;
514                         break;
515                 }
516         }
517         usbd_free_xfer(xfer);
518
519         return (error);
520 }
521
522 int
523 ulptwrite(dev_t dev, struct uio *uio, int flags)
524 {
525         struct ulpt_softc *sc;
526         int error;
527
528         USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
529
530         if (sc->sc_dying)
531                 return (EIO);
532
533         sc->sc_refcnt++;
534         error = ulpt_do_write(sc, uio, flags);
535         if (--sc->sc_refcnt < 0)
536                 usb_detach_wakeup(USBDEV(sc->sc_dev));
537         return (error);
538 }
539
540 int
541 ulptioctl(dev_t dev, u_long cmd, caddr_t data, int flag, usb_proc_ptr p)
542 {
543         int error = 0;
544
545         switch (cmd) {
546         default:
547                 error = ENODEV;
548         }
549
550         return (error);
551 }
552
553 #if 0
554 /* XXX This does not belong here. */
555 /*
556  * Print select parts of a IEEE 1284 device ID.
557  */
558 void
559 ieee1284_print_id(char *str)
560 {
561         char *p, *q;
562
563         for (p = str-1; p; p = strchr(p, ';')) {
564                 p++;            /* skip ';' */
565                 if (strncmp(p, "MFG:", 4) == 0 ||
566                     strncmp(p, "MANUFACTURER:", 14) == 0 ||
567                     strncmp(p, "MDL:", 4) == 0 ||
568                     strncmp(p, "MODEL:", 6) == 0) {
569                         q = strchr(p, ';');
570                         if (q)
571                                 printf("%.*s", (int)(q - p + 1), p);
572                 }
573         }
574 }
575 #endif
576
577 #if defined(__FreeBSD__)
578 DRIVER_MODULE(ulpt, uhub, ulpt_driver, ulpt_devclass, usbd_driver_load, 0);
579 #endif