Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / dev / misc / lpt / lpt.c
1 /*
2  * Copyright (c) 1990 William F. Jolitz, TeleMuse
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This software is a component of "386BSD" developed by
16  *      William F. Jolitz, TeleMuse.
17  * 4. Neither the name of the developer nor the name "386BSD"
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS A COMPONENT OF 386BSD DEVELOPED BY WILLIAM F. JOLITZ
22  * AND IS INTENDED FOR RESEARCH AND EDUCATIONAL PURPOSES ONLY. THIS
23  * SOFTWARE SHOULD NOT BE CONSIDERED TO BE A COMMERCIAL PRODUCT.
24  * THE DEVELOPER URGES THAT USERS WHO REQUIRE A COMMERCIAL PRODUCT
25  * NOT MAKE USE OF THIS WORK.
26  *
27  * FOR USERS WHO WISH TO UNDERSTAND THE 386BSD SYSTEM DEVELOPED
28  * BY WILLIAM F. JOLITZ, WE RECOMMEND THE USER STUDY WRITTEN
29  * REFERENCES SUCH AS THE  "PORTING UNIX TO THE 386" SERIES
30  * (BEGINNING JANUARY 1991 "DR. DOBBS JOURNAL", USA AND BEGINNING
31  * JUNE 1991 "UNIX MAGAZIN", GERMANY) BY WILLIAM F. JOLITZ AND
32  * LYNNE GREER JOLITZ, AS WELL AS OTHER BOOKS ON UNIX AND THE
33  * ON-LINE 386BSD USER MANUAL BEFORE USE. A BOOK DISCUSSING THE INTERNALS
34  * OF 386BSD ENTITLED "386BSD FROM THE INSIDE OUT" WILL BE AVAILABLE LATE 1992.
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE DEVELOPER ``AS IS'' AND
37  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
39  * ARE DISCLAIMED.  IN NO EVENT SHALL THE DEVELOPER BE LIABLE
40  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
41  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
42  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
44  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
45  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  *
48  *      from: unknown origin, 386BSD 0.1
49  *      From Id: lpt.c,v 1.55.2.1 1996/11/12 09:08:38 phk Exp
50  *      From Id: nlpt.c,v 1.14 1999/02/08 13:55:43 des Exp
51  * $FreeBSD: src/sys/dev/ppbus/lpt.c,v 1.15.2.3 2000/07/07 00:30:40 obrien Exp $
52  */
53
54 /*
55  * Device Driver for AT parallel printer port
56  * Written by William Jolitz 12/18/90
57  */
58
59 /*
60  * Updated for ppbus by Nicolas Souchu
61  * [Mon Jul 28 1997]
62  */
63
64 #include "opt_lpt.h"
65
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/module.h>
69 #include <sys/bus.h>
70 #include <sys/conf.h>
71 #include <sys/kernel.h>
72 #include <sys/uio.h>
73 #include <sys/syslog.h>
74 #include <sys/malloc.h>
75
76 #include <machine/clock.h>
77 #include <machine/bus.h>
78 #include <machine/resource.h>
79 #include <sys/rman.h>
80
81 #include <dev/ppbus/lptio.h>
82 #include <dev/ppbus/ppbconf.h>
83 #include <dev/ppbus/ppb_1284.h>
84 #include <dev/ppbus/lpt.h>
85 #include "ppbus_if.h"
86 #include <dev/ppbus/ppbio.h>
87
88 MALLOC_DEFINE(M_LPT, "lpt", "LPT buffers");
89
90 #ifndef LPT_DEBUG
91 #define lprintf(args)
92 #else
93 #define lprintf(args)                                           \
94                 do {                                            \
95                         if (lptflag)                            \
96                                 printf args;                    \
97                 } while (0)
98 static int volatile lptflag = 1;
99 #endif
100
101 #define LPINITRDY       4       /* wait up to 4 seconds for a ready */
102 #define LPTOUTINITIAL   10      /* initial timeout to wait for ready 1/10 s */
103 #define LPTOUTMAX       1       /* maximal timeout 1 s */
104 #define LPPRI           (PZERO+8)
105 #define BUFSIZE         1024
106 #define BUFSTATSIZE     32
107
108 #define LPTUNIT(s)      ((s)&0x03)
109 #define LPTFLAGS(s)     ((s)&0xfc)
110
111 struct lpt_data {
112
113         short   sc_state;
114         /* default case: negative prime, negative ack, handshake strobe,
115            prime once */
116         u_char  sc_control;
117         char    sc_flags;
118 #define LP_POS_INIT     0x04    /* if we are a postive init signal */
119 #define LP_POS_ACK      0x08    /* if we are a positive going ack */
120 #define LP_NO_PRIME     0x10    /* don't prime the printer at all */
121 #define LP_PRIMEOPEN    0x20    /* prime on every open */
122 #define LP_AUTOLF       0x40    /* tell printer to do an automatic lf */
123 #define LP_BYPASS       0x80    /* bypass  printer ready checks */
124         void    *sc_inbuf;
125         void    *sc_statbuf;
126         short   sc_xfercnt ;
127         char    sc_primed;
128         char    *sc_cp ;
129         u_short sc_irq ;        /* IRQ status of port */
130 #define LP_HAS_IRQ      0x01    /* we have an irq available */
131 #define LP_USE_IRQ      0x02    /* we are using our irq */
132 #define LP_ENABLE_IRQ   0x04    /* enable IRQ on open */
133 #define LP_ENABLE_EXT   0x10    /* we shall use advanced mode when possible */
134         u_char  sc_backoff ;    /* time to call lptout() again */
135
136         struct resource *intr_resource; /* interrupt resource */
137         void *intr_cookie;              /* interrupt registration cookie */
138
139 };
140
141 #define LPT_NAME        "lpt"           /* our official name */
142
143 static timeout_t lptout;
144 static int      lpt_port_test(device_t dev, u_char data, u_char mask);
145 static int      lpt_detect(device_t dev);
146
147 #define DEVTOSOFTC(dev) \
148         ((struct lpt_data *)device_get_softc(dev))
149 #define UNITOSOFTC(unit) \
150         ((struct lpt_data *)devclass_get_softc(lpt_devclass, (unit)))
151 #define UNITODEVICE(unit) \
152         (devclass_get_device(lpt_devclass, (unit)))
153
154 static void lptintr(device_t dev);
155 static void lpt_intr(void *arg);        /* without spls */
156
157 static devclass_t lpt_devclass;
158
159
160 /* bits for state */
161 #define OPEN            (1<<0)  /* device is open */
162 #define ASLP            (1<<1)  /* awaiting draining of printer */
163 #define EERROR          (1<<2)  /* error was received from printer */
164 #define OBUSY           (1<<3)  /* printer is busy doing output */
165 #define LPTOUT          (1<<4)  /* timeout while not selected */
166 #define TOUT            (1<<5)  /* timeout while not selected */
167 #define LPTINIT         (1<<6)  /* waiting to initialize for open */
168 #define INTERRUPTED     (1<<7)  /* write call was interrupted */
169
170 #define HAVEBUS         (1<<8)  /* the driver owns the bus */
171
172
173 /* status masks to interrogate printer status */
174 #define RDY_MASK        (LPS_SEL|LPS_OUT|LPS_NBSY|LPS_NERR)     /* ready ? */
175 #define LP_READY        (LPS_SEL|LPS_NBSY|LPS_NERR)
176
177 /* Printer Ready condition  - from lpa.c */
178 /* Only used in polling code */
179 #define LPS_INVERT      (LPS_NBSY | LPS_NACK |           LPS_SEL | LPS_NERR)
180 #define LPS_MASK        (LPS_NBSY | LPS_NACK | LPS_OUT | LPS_SEL | LPS_NERR)
181 #define NOT_READY(ppbus) ((ppb_rstr(ppbus)^LPS_INVERT)&LPS_MASK)
182
183 #define MAX_SLEEP       (hz*5)  /* Timeout while waiting for device ready */
184 #define MAX_SPIN        20      /* Max delay for device ready in usecs */
185
186
187 static  d_open_t        lptopen;
188 static  d_close_t       lptclose;
189 static  d_write_t       lptwrite;
190 static  d_read_t        lptread;
191 static  d_ioctl_t       lptioctl;
192
193 #define CDEV_MAJOR 16
194 static struct cdevsw lpt_cdevsw = {
195         /* open */      lptopen,
196         /* close */     lptclose,
197         /* read */      lptread,
198         /* write */     lptwrite,
199         /* ioctl */     lptioctl,
200         /* poll */      nopoll,
201         /* mmap */      nommap,
202         /* strategy */  nostrategy,
203         /* name */      LPT_NAME,
204         /* maj */       CDEV_MAJOR,
205         /* dump */      nodump,
206         /* psize */     nopsize,
207         /* flags */     0,
208         /* bmaj */      -1
209 };
210
211 static int
212 lpt_request_ppbus(device_t dev, int how)
213 {
214         device_t ppbus = device_get_parent(dev);
215         struct lpt_data *sc = DEVTOSOFTC(dev);
216         int error;
217
218         if (sc->sc_state & HAVEBUS)
219                 return (0);
220
221         /* we have the bus only if the request succeded */
222         if ((error = ppb_request_bus(ppbus, dev, how)) == 0)
223                 sc->sc_state |= HAVEBUS;
224
225         return (error);
226 }
227
228 static int
229 lpt_release_ppbus(device_t dev)
230 {
231         device_t ppbus = device_get_parent(dev);
232         struct lpt_data *sc = DEVTOSOFTC(dev);
233         int error = 0;
234
235         if ((error = ppb_release_bus(ppbus, dev)) == 0)
236                 sc->sc_state &= ~HAVEBUS;
237
238         return (error);
239 }
240
241 /*
242  * Internal routine to lptprobe to do port tests of one byte value
243  */
244 static int
245 lpt_port_test(device_t ppbus, u_char data, u_char mask)
246 {
247         int     temp, timeout;
248
249         data = data & mask;
250         ppb_wdtr(ppbus, data);
251         timeout = 10000;
252         do {
253                 DELAY(10);
254                 temp = ppb_rdtr(ppbus) & mask;
255         }
256         while (temp != data && --timeout);
257         lprintf(("out=%x\tin=%x\ttout=%d\n", data, temp, timeout));
258         return (temp == data);
259 }
260
261 /*
262  * Probe simplified by replacing multiple loops with a hardcoded
263  * test pattern - 1999/02/08 des@freebsd.org
264  *
265  * New lpt port probe Geoff Rehmet - Rhodes University - 14/2/94
266  * Based partially on Rod Grimes' printer probe
267  *
268  * Logic:
269  *      1) If no port address was given, use the bios detected ports
270  *         and autodetect what ports the printers are on.
271  *      2) Otherwise, probe the data port at the address given,
272  *         using the method in Rod Grimes' port probe.
273  *         (Much code ripped off directly from Rod's probe.)
274  *
275  * Comments from Rod's probe:
276  * Logic:
277  *      1) You should be able to write to and read back the same value
278  *         to the data port.  Do an alternating zeros, alternating ones,
279  *         walking zero, and walking one test to check for stuck bits.
280  *
281  *      2) You should be able to write to and read back the same value
282  *         to the control port lower 5 bits, the upper 3 bits are reserved
283  *         per the IBM PC technical reference manauls and different boards
284  *         do different things with them.  Do an alternating zeros, alternating
285  *         ones, walking zero, and walking one test to check for stuck bits.
286  *
287  *         Some printers drag the strobe line down when the are powered off
288  *         so this bit has been masked out of the control port test.
289  *
290  *         XXX Some printers may not like a fast pulse on init or strobe, I
291  *         don't know at this point, if that becomes a problem these bits
292  *         should be turned off in the mask byte for the control port test.
293  *
294  *         We are finally left with a mask of 0x14, due to some printers
295  *         being adamant about holding other bits high ........
296  *
297  *         Before probing the control port, we write a 0 to the data port -
298  *         If not, some printers chuck out garbage when the strobe line
299  *         gets toggled.
300  *
301  *      3) Set the data and control ports to a value of 0
302  *
303  *      This probe routine has been tested on Epson Lx-800, HP LJ3P,
304  *      Epson FX-1170 and C.Itoh 8510RM
305  *      printers.
306  *      Quick exit on fail added.
307  */
308 static int
309 lpt_detect(device_t dev)
310 {
311         device_t ppbus = device_get_parent(dev);
312
313         static u_char   testbyte[18] = {
314                 0x55,                   /* alternating zeros */
315                 0xaa,                   /* alternating ones */
316                 0xfe, 0xfd, 0xfb, 0xf7,
317                 0xef, 0xdf, 0xbf, 0x7f, /* walking zero */
318                 0x01, 0x02, 0x04, 0x08,
319                 0x10, 0x20, 0x40, 0x80  /* walking one */
320         };
321         int             i, error, status;
322
323         status = 1;                             /* assume success */
324
325         if ((error = lpt_request_ppbus(dev, PPB_DONTWAIT))) {
326                 printf(LPT_NAME ": cannot alloc ppbus (%d)!\n", error);
327                 status = 0;
328                 goto end_probe;
329         }
330
331         for (i = 0; i < 18 && status; i++)
332                 if (!lpt_port_test(ppbus, testbyte[i], 0xff)) {
333                         status = 0;
334                         goto end_probe;
335                 }
336
337 end_probe:
338         /* write 0's to control and data ports */
339         ppb_wdtr(ppbus, 0);
340         ppb_wctr(ppbus, 0);
341
342         lpt_release_ppbus(dev);
343
344         return (status);
345 }
346
347 static void
348 lpt_identify(driver_t *driver, device_t parent)
349 {
350
351         BUS_ADD_CHILD(parent, 0, LPT_NAME, 0);
352 }
353
354 /*
355  * lpt_probe()
356  */
357 static int
358 lpt_probe(device_t dev)
359 {
360         struct lpt_data *sc;
361         
362         sc = DEVTOSOFTC(dev);
363         bzero(sc, sizeof(struct lpt_data));
364
365         /*
366          * Now, try to detect the printer.
367          */
368         if (!lpt_detect(dev))
369                 return (ENXIO);
370
371         device_set_desc(dev, "Printer");
372
373         return (0);
374 }
375
376 static int
377 lpt_attach(device_t dev)
378 {
379         device_t ppbus = device_get_parent(dev);
380         struct lpt_data *sc = DEVTOSOFTC(dev);
381         int zero = 0, unit = device_get_unit(dev);
382         int error;
383         uintptr_t irq;
384
385         sc->sc_primed = 0;      /* not primed yet */
386
387         if ((error = lpt_request_ppbus(dev, PPB_DONTWAIT))) {
388                 printf(LPT_NAME ": cannot alloc ppbus (%d)!\n", error);
389                 return (0);
390         }
391
392         ppb_wctr(ppbus, LPC_NINIT);
393
394         /* check if we can use interrupt, should be done by ppc stuff */
395         lprintf(("oldirq %x\n", sc->sc_irq));
396
397         /* retrieve the ppbus irq */
398         BUS_READ_IVAR(ppbus, dev, PPBUS_IVAR_IRQ, &irq);
399
400         if (irq > 0) {
401                 /* declare our interrupt handler */
402                 sc->intr_resource = bus_alloc_resource(dev, SYS_RES_IRQ,
403                                                        &zero, irq, irq, 1, RF_SHAREABLE);
404         }
405         if (sc->intr_resource) {
406                 sc->sc_irq = LP_HAS_IRQ | LP_USE_IRQ | LP_ENABLE_IRQ;
407                 device_printf(dev, "Interrupt-driven port\n");
408         } else {
409                 sc->sc_irq = 0;
410                 device_printf(dev, "Polled port\n");
411         }
412         lprintf(("irq %x %x\n", irq, sc->sc_irq));
413
414         lpt_release_ppbus(dev);
415
416         make_dev(&lpt_cdevsw, unit,
417             UID_ROOT, GID_WHEEL, 0600, LPT_NAME "%d", unit);
418         make_dev(&lpt_cdevsw, unit | LP_BYPASS,
419             UID_ROOT, GID_WHEEL, 0600, LPT_NAME "%d.ctl", unit);
420         return (0);
421 }
422
423 static void
424 lptout(void *arg)
425 {
426         device_t dev = (device_t)arg;
427         struct lpt_data *sc = DEVTOSOFTC(dev);
428 #ifdef LPT_DEBUG
429         device_t ppbus = device_get_parent(dev);
430 #endif
431
432         lprintf(("T %x ", ppb_rstr(ppbus)));
433         if (sc->sc_state & OPEN) {
434                 sc->sc_backoff++;
435                 if (sc->sc_backoff > hz/LPTOUTMAX)
436                         sc->sc_backoff = sc->sc_backoff > hz/LPTOUTMAX;
437                 timeout(lptout, (caddr_t)dev, sc->sc_backoff);
438         } else
439                 sc->sc_state &= ~TOUT;
440
441         if (sc->sc_state & EERROR)
442                 sc->sc_state &= ~EERROR;
443
444         /*
445          * Avoid possible hangs due to missed interrupts
446          */
447         if (sc->sc_xfercnt) {
448                 lptintr(dev);
449         } else {
450                 sc->sc_state &= ~OBUSY;
451                 wakeup((caddr_t)dev);
452         }
453 }
454
455 /*
456  * lptopen -- reset the printer, then wait until it's selected and not busy.
457  *      If LP_BYPASS flag is selected, then we do not try to select the
458  *      printer -- this is just used for passing ioctls.
459  */
460
461 static  int
462 lptopen(dev_t dev, int flags, int fmt, struct proc *p)
463 {
464         int s;
465         int trys, err;
466         u_int unit = LPTUNIT(minor(dev));
467         struct lpt_data *sc = UNITOSOFTC(unit);
468         device_t lptdev = UNITODEVICE(unit);
469         device_t ppbus = device_get_parent(lptdev);
470
471         if (!sc)
472                 return (ENXIO);
473
474         if (sc->sc_state) {
475                 lprintf((LPT_NAME ": still open %x\n", sc->sc_state));
476                 return(EBUSY);
477         } else
478                 sc->sc_state |= LPTINIT;
479
480         sc->sc_flags = LPTFLAGS(minor(dev));
481
482         /* Check for open with BYPASS flag set. */
483         if (sc->sc_flags & LP_BYPASS) {
484                 sc->sc_state = OPEN;
485                 return(0);
486         }
487
488         /* request the ppbus only if we don't have it already */
489         if ((err = lpt_request_ppbus(lptdev, PPB_WAIT|PPB_INTR)) != 0) {
490                 /* give it a chance to try later */
491                 sc->sc_state = 0;
492                 return (err);
493         }
494
495         s = spltty();
496         lprintf((LPT_NAME " flags 0x%x\n", sc->sc_flags));
497
498         /* set IRQ status according to ENABLE_IRQ flag
499          */
500         if (sc->sc_irq & LP_ENABLE_IRQ)
501                 sc->sc_irq |= LP_USE_IRQ;
502         else
503                 sc->sc_irq &= ~LP_USE_IRQ;
504
505         /* init printer */
506         if ((sc->sc_flags & LP_NO_PRIME) == 0) {
507                 if((sc->sc_flags & LP_PRIMEOPEN) || sc->sc_primed == 0) {
508                         ppb_wctr(ppbus, 0);
509                         sc->sc_primed++;
510                         DELAY(500);
511                 }
512         }
513
514         ppb_wctr(ppbus, LPC_SEL|LPC_NINIT);
515
516         /* wait till ready (printer running diagnostics) */
517         trys = 0;
518         do {
519                 /* ran out of waiting for the printer */
520                 if (trys++ >= LPINITRDY*4) {
521                         splx(s);
522                         sc->sc_state = 0;
523                         lprintf(("status %x\n", ppb_rstr(ppbus)));
524
525                         lpt_release_ppbus(lptdev);
526                         return (EBUSY);
527                 }
528
529                 /* wait 1/4 second, give up if we get a signal */
530                 if (tsleep((caddr_t)lptdev, LPPRI|PCATCH, "lptinit", hz/4) !=
531                     EWOULDBLOCK) {
532                         sc->sc_state = 0;
533                         splx(s);
534
535                         lpt_release_ppbus(lptdev);
536                         return (EBUSY);
537                 }
538
539                 /* is printer online and ready for output */
540         } while ((ppb_rstr(ppbus) &
541                         (LPS_SEL|LPS_OUT|LPS_NBSY|LPS_NERR)) !=
542                                         (LPS_SEL|LPS_NBSY|LPS_NERR));
543
544         sc->sc_control = LPC_SEL|LPC_NINIT;
545         if (sc->sc_flags & LP_AUTOLF)
546                 sc->sc_control |= LPC_AUTOL;
547
548         /* enable interrupt if interrupt-driven */
549         if (sc->sc_irq & LP_USE_IRQ)
550                 sc->sc_control |= LPC_ENA;
551
552         ppb_wctr(ppbus, sc->sc_control);
553
554         sc->sc_state = OPEN;
555         sc->sc_inbuf = malloc(BUFSIZE, M_LPT, M_WAITOK);
556         sc->sc_statbuf = malloc(BUFSTATSIZE, M_LPT, M_WAITOK);
557         sc->sc_xfercnt = 0;
558         splx(s);
559
560         /* release the ppbus */
561         lpt_release_ppbus(lptdev);
562
563         /* only use timeout if using interrupt */
564         lprintf(("irq %x\n", sc->sc_irq));
565         if (sc->sc_irq & LP_USE_IRQ) {
566                 sc->sc_state |= TOUT;
567                 timeout(lptout, (caddr_t)lptdev,
568                          (sc->sc_backoff = hz/LPTOUTINITIAL));
569         }
570
571         lprintf(("opened.\n"));
572         return(0);
573 }
574
575 /*
576  * lptclose -- close the device, free the local line buffer.
577  *
578  * Check for interrupted write call added.
579  */
580
581 static  int
582 lptclose(dev_t dev, int flags, int fmt, struct proc *p)
583 {
584         u_int unit = LPTUNIT(minor(dev));
585         struct lpt_data *sc = UNITOSOFTC(unit);
586         device_t lptdev = UNITODEVICE(unit);
587         device_t ppbus = device_get_parent(lptdev);
588         int err;
589
590         if(sc->sc_flags & LP_BYPASS)
591                 goto end_close;
592
593         if ((err = lpt_request_ppbus(lptdev, PPB_WAIT|PPB_INTR)) != 0)
594                 return (err);
595
596         sc->sc_state &= ~OPEN;
597
598         /* if the last write was interrupted, don't complete it */
599         if((!(sc->sc_state  & INTERRUPTED)) && (sc->sc_irq & LP_USE_IRQ))
600                 while ((ppb_rstr(ppbus) &
601                         (LPS_SEL|LPS_OUT|LPS_NBSY|LPS_NERR)) !=
602                         (LPS_SEL|LPS_NBSY|LPS_NERR) || sc->sc_xfercnt)
603                         /* wait 1/4 second, give up if we get a signal */
604                         if (tsleep((caddr_t)lptdev, LPPRI|PCATCH,
605                                 "lpclose", hz) != EWOULDBLOCK)
606                                 break;
607
608         ppb_wctr(ppbus, LPC_NINIT);
609         free(sc->sc_inbuf, M_LPT);
610         free(sc->sc_statbuf, M_LPT);
611
612 end_close:
613         /* release the bus anyway
614          * unregistration of interrupt forced by release
615          */
616         lpt_release_ppbus(lptdev);
617
618         sc->sc_state = 0;
619         sc->sc_xfercnt = 0;
620         lprintf(("closed.\n"));
621         return(0);
622 }
623
624 /*
625  * lpt_pushbytes()
626  *      Workhorse for actually spinning and writing bytes to printer
627  *      Derived from lpa.c
628  *      Originally by ?
629  *
630  *      This code is only used when we are polling the port
631  */
632 static int
633 lpt_pushbytes(device_t dev)
634 {
635         struct lpt_data *sc = DEVTOSOFTC(dev);
636         device_t ppbus = device_get_parent(dev);
637         int spin, err, tic;
638         char ch;
639
640         lprintf(("p"));
641         /* loop for every character .. */
642         while (sc->sc_xfercnt > 0) {
643                 /* printer data */
644                 ch = *(sc->sc_cp);
645                 sc->sc_cp++;
646                 sc->sc_xfercnt--;
647
648                 /*
649                  * Wait for printer ready.
650                  * Loop 20 usecs testing BUSY bit, then sleep
651                  * for exponentially increasing timeout. (vak)
652                  */
653                 for (spin = 0; NOT_READY(ppbus) && spin < MAX_SPIN; ++spin)
654                         DELAY(1);       /* XXX delay is NOT this accurate! */
655                 if (spin >= MAX_SPIN) {
656                         tic = 0;
657                         while (NOT_READY(ppbus)) {
658                                 /*
659                                  * Now sleep, every cycle a
660                                  * little longer ..
661                                  */
662                                 tic = tic + tic + 1;
663                                 /*
664                                  * But no more than 10 seconds. (vak)
665                                  */
666                                 if (tic > MAX_SLEEP)
667                                         tic = MAX_SLEEP;
668                                 err = tsleep((caddr_t)dev, LPPRI,
669                                         LPT_NAME "poll", tic);
670                                 if (err != EWOULDBLOCK) {
671                                         return (err);
672                                 }
673                         }
674                 }
675
676                 /* output data */
677                 ppb_wdtr(ppbus, ch);
678                 /* strobe */
679                 ppb_wctr(ppbus, sc->sc_control|LPC_STB);
680                 ppb_wctr(ppbus, sc->sc_control);
681
682         }
683         return(0);
684 }
685
686 /*
687  * lptread --retrieve printer status in IEEE1284 NIBBLE mode
688  */
689
690 static int
691 lptread(dev_t dev, struct uio *uio, int ioflag)
692 {
693         u_int   unit = LPTUNIT(minor(dev));
694         struct lpt_data *sc = UNITOSOFTC(unit);
695         device_t lptdev = UNITODEVICE(unit);
696         device_t ppbus = device_get_parent(lptdev);
697         int error = 0, len;
698
699         if (sc->sc_flags & LP_BYPASS) {
700                 /* we can't do reads in bypass mode */
701                 return (EPERM);
702         }
703
704         if ((error = ppb_1284_negociate(ppbus, PPB_NIBBLE, 0)))
705                 return (error);
706
707         /* read data in an other buffer, read/write may be simultaneous */
708         len = 0;
709         while (uio->uio_resid) {
710                 if ((error = ppb_1284_read(ppbus, PPB_NIBBLE,
711                                 sc->sc_statbuf, min(BUFSTATSIZE,
712                                 uio->uio_resid), &len))) {
713                         goto error;
714                 }
715
716                 if (!len)
717                         goto error;             /* no more data */
718
719                 if ((error = uiomove(sc->sc_statbuf, len, uio)))
720                         goto error;
721         }
722
723 error:
724         ppb_1284_terminate(ppbus);
725         return (error);
726 }
727
728 /*
729  * lptwrite --copy a line from user space to a local buffer, then call
730  * putc to get the chars moved to the output queue.
731  *
732  * Flagging of interrupted write added.
733  */
734
735 static  int
736 lptwrite(dev_t dev, struct uio *uio, int ioflag)
737 {
738         register unsigned n;
739         int err;
740         u_int   unit = LPTUNIT(minor(dev));
741         struct lpt_data *sc = UNITOSOFTC(unit);
742         device_t lptdev = UNITODEVICE(unit);
743         device_t ppbus = device_get_parent(lptdev);
744
745         if(sc->sc_flags & LP_BYPASS) {
746                 /* we can't do writes in bypass mode */
747                 return(EPERM);
748         }
749
750         /* request the ppbus only if we don't have it already */
751         /* XXX interrupt registration?! */
752         if ((err = lpt_request_ppbus(lptdev, PPB_WAIT|PPB_INTR)) != 0)
753                 return (err);
754
755         /* if interrupts are working, register the handler */
756         if (sc->sc_irq & LP_USE_IRQ) {
757                 /* register our interrupt handler */
758                 err = BUS_SETUP_INTR(ppbus, lptdev, sc->intr_resource,
759                                INTR_TYPE_TTY, lpt_intr, lptdev,
760                                &sc->intr_cookie);
761                 if (err) {
762                         device_printf(lptdev, "handler registration failed, polled mode.\n");
763                         sc->sc_irq &= ~LP_USE_IRQ;
764                 }
765         }
766
767         sc->sc_state &= ~INTERRUPTED;
768         while ((n = min(BUFSIZE, uio->uio_resid)) != 0) {
769                 sc->sc_cp = sc->sc_inbuf;
770                 uiomove(sc->sc_cp, n, uio);
771                 sc->sc_xfercnt = n ;
772
773                 if (sc->sc_irq & LP_ENABLE_EXT) {
774                         /* try any extended mode */
775                         err = ppb_write(ppbus, sc->sc_cp,
776                                         sc->sc_xfercnt, 0);
777                         switch (err) {
778                         case 0:
779                                 /* if not all data was sent, we could rely
780                                  * on polling for the last bytes */
781                                 sc->sc_xfercnt = 0;
782                                 break;
783                         case EINTR:
784                                 sc->sc_state |= INTERRUPTED;    
785                                 return(err);
786                         case EINVAL:
787                                 /* advanced mode not avail */
788                                 log(LOG_NOTICE, LPT_NAME "%d: advanced mode not avail, polling\n", unit);
789                                 break;
790                         default:
791                                 return(err);
792                         }
793                 } else while ((sc->sc_xfercnt > 0)&&(sc->sc_irq & LP_USE_IRQ)) {
794                         lprintf(("i"));
795                         /* if the printer is ready for a char, */
796                         /* give it one */
797                         if ((sc->sc_state & OBUSY) == 0){
798                                 lprintf(("\nC %d. ", sc->sc_xfercnt));
799                                 lptintr(lptdev);
800                         }
801                         lprintf(("W "));
802                         if (sc->sc_state & OBUSY)
803                                 if ((err = tsleep((caddr_t)lptdev,
804                                          LPPRI|PCATCH, LPT_NAME "write", 0))) {
805                                         sc->sc_state |= INTERRUPTED;
806                                         return(err);
807                                 }
808                 }
809
810                 /* check to see if we must do a polled write */
811                 if(!(sc->sc_irq & LP_USE_IRQ) && (sc->sc_xfercnt)) {
812                         lprintf(("p"));
813
814                         err = lpt_pushbytes(lptdev);
815
816                         if (err)
817                                 return(err);
818                 }
819         }
820
821         /* we have not been interrupted, release the ppbus */
822         lpt_release_ppbus(lptdev);
823
824         return(0);
825 }
826
827 /*
828  * lpt_intr -- handle printer interrupts which occur when the printer is
829  * ready to accept another char.
830  *
831  * do checking for interrupted write call.
832  */
833
834 static void
835 lpt_intr(void *arg)
836 {
837         device_t lptdev = (device_t)arg;
838         device_t ppbus = device_get_parent(lptdev);
839         struct lpt_data *sc = DEVTOSOFTC(lptdev);
840         int sts = 0;
841         int i;
842         
843         /* we must own the bus to use it */
844         if ((sc->sc_state & HAVEBUS) == 0)
845                 return;
846
847         /*
848          * Is printer online and ready for output?
849          *
850          * Avoid falling back to lptout() too quickly.  First spin-loop
851          * to see if the printer will become ready ``really soon now''.
852          */
853         for (i = 0; i < 100 &&
854              ((sts=ppb_rstr(ppbus)) & RDY_MASK) != LP_READY; i++) ;
855
856         if ((sts & RDY_MASK) == LP_READY) {
857                 sc->sc_state = (sc->sc_state | OBUSY) & ~EERROR;
858                 sc->sc_backoff = hz/LPTOUTINITIAL;
859
860                 if (sc->sc_xfercnt) {
861                         /* send char */
862                         /*lprintf(("%x ", *sc->sc_cp)); */
863                         ppb_wdtr(ppbus, *sc->sc_cp++) ;
864                         ppb_wctr(ppbus, sc->sc_control|LPC_STB);
865                         /* DELAY(X) */
866                         ppb_wctr(ppbus, sc->sc_control);
867
868                         /* any more data for printer */
869                         if(--(sc->sc_xfercnt) > 0) return;
870                 }
871
872                 /*
873                  * No more data waiting for printer.
874                  * Wakeup is not done if write call was not interrupted.
875                  */
876                 sc->sc_state &= ~OBUSY;
877
878                 if(!(sc->sc_state & INTERRUPTED))
879                         wakeup((caddr_t)lptdev);
880                 lprintf(("w "));
881                 return;
882         } else  {       /* check for error */
883                 if(((sts & (LPS_NERR | LPS_OUT) ) != LPS_NERR) &&
884                                 (sc->sc_state & OPEN))
885                         sc->sc_state |= EERROR;
886                 /* lptout() will jump in and try to restart. */
887         }
888         lprintf(("sts %x ", sts));
889 }
890
891 static void
892 lptintr(device_t dev)
893 {
894         /* call the interrupt at required spl level */
895         int s = spltty();
896
897         lpt_intr(dev);
898
899         splx(s);
900         return;
901 }
902
903 static  int
904 lptioctl(dev_t dev, u_long cmd, caddr_t data, int flags, struct proc *p)
905 {
906         int     error = 0;
907         u_int   unit = LPTUNIT(minor(dev));
908         struct  lpt_data *sc = UNITOSOFTC(unit);
909         u_char  old_sc_irq;     /* old printer IRQ status */
910
911         switch (cmd) {
912         case LPT_IRQ :
913                 if(sc->sc_irq & LP_HAS_IRQ) {
914                         /*
915                          * NOTE:
916                          * If the IRQ status is changed,
917                          * this will only be visible on the
918                          * next open.
919                          *
920                          * If interrupt status changes,
921                          * this gets syslog'd.
922                          */
923                         old_sc_irq = sc->sc_irq;
924                         switch(*(int*)data) {
925                         case 0:
926                                 sc->sc_irq &= (~LP_ENABLE_IRQ);
927                                 break;
928                         case 1:
929                                 sc->sc_irq &= (~LP_ENABLE_EXT);
930                                 sc->sc_irq |= LP_ENABLE_IRQ;
931                                 break;
932                         case 2:
933                                 /* classic irq based transfer and advanced
934                                  * modes are in conflict
935                                  */
936                                 sc->sc_irq &= (~LP_ENABLE_IRQ);
937                                 sc->sc_irq |= LP_ENABLE_EXT;
938                                 break;
939                         case 3:
940                                 sc->sc_irq &= (~LP_ENABLE_EXT);
941                                 break;
942                         default:
943                                 break;
944                         }
945                                 
946                         if (old_sc_irq != sc->sc_irq )
947                                 log(LOG_NOTICE, LPT_NAME "%d: switched to %s %s mode\n",
948                                         unit,
949                                         (sc->sc_irq & LP_ENABLE_IRQ)?
950                                         "interrupt-driven":"polled",
951                                         (sc->sc_irq & LP_ENABLE_EXT)?
952                                         "extended":"standard");
953                 } else /* polled port */
954                         error = EOPNOTSUPP;
955                 break;
956         default:
957                 error = ENODEV;
958         }
959
960         return(error);
961 }
962
963 static device_method_t lpt_methods[] = {
964         /* device interface */
965         DEVMETHOD(device_identify,      lpt_identify),
966         DEVMETHOD(device_probe,         lpt_probe),
967         DEVMETHOD(device_attach,        lpt_attach),
968
969         { 0, 0 }
970 };
971
972 static driver_t lpt_driver = {
973         LPT_NAME,
974         lpt_methods,
975         sizeof(struct lpt_data),
976 };
977
978 DRIVER_MODULE(lpt, ppbus, lpt_driver, lpt_devclass, 0, 0);