xref: /dragonfly/sys/dev/misc/lpt/lpt.c (revision 19b217af)
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/device.h>
72 #include <sys/kernel.h>
73 #include <sys/uio.h>
74 #include <sys/syslog.h>
75 #include <sys/thread2.h>
76 #include <sys/malloc.h>
77 #include <sys/rman.h>
78 
79 #include <machine/clock.h>
80 #include <machine/inttypes.h>
81 
82 #include "lptio.h"
83 #include <bus/ppbus/ppbconf.h>
84 #include <bus/ppbus/ppb_1284.h>
85 #include "lpt.h"
86 #include "ppbus_if.h"
87 #include <bus/ppbus/ppbio.h>
88 
89 MALLOC_DEFINE(M_LPT, "lpt", "LPT buffers");
90 
91 #ifndef LPT_DEBUG
92 #define lprintf(args)
93 #else
94 #define lprintf(args)						\
95 		do {						\
96 			if (lptflag)				\
97 				kprintf args;			\
98 		} while (0)
99 static int volatile lptflag = 1;
100 #endif
101 
102 #define	LPINITRDY	4	/* wait up to 4 seconds for a ready */
103 #define	LPTOUTINITIAL	10	/* initial timeout to wait for ready 1/10 s */
104 #define	LPTOUTMAX	1	/* maximal timeout 1 s */
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 	short	sc_state;
113 	/* default case: negative prime, negative ack, handshake strobe,
114 	   prime once */
115 	u_char	sc_control;
116 	char	sc_flags;
117 #define LP_UNITMASK	0x03	/* up to 4 units */
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 	struct callout	sc_callout;
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 static struct dev_ops lpt_ops = {
194 	{ LPT_NAME, 0, 0 },
195 	.d_open =	lptopen,
196 	.d_close =	lptclose,
197 	.d_read =	lptread,
198 	.d_write =	lptwrite,
199 	.d_ioctl =	lptioctl,
200 };
201 
202 static int
203 lpt_request_ppbus(device_t dev, int how)
204 {
205 	device_t ppbus = device_get_parent(dev);
206 	struct lpt_data *sc = DEVTOSOFTC(dev);
207 	int error;
208 
209 	if (sc->sc_state & HAVEBUS)
210 		return (0);
211 
212 	/* we have the bus only if the request succeded */
213 	if ((error = ppb_request_bus(ppbus, dev, how)) == 0)
214 		sc->sc_state |= HAVEBUS;
215 
216 	return (error);
217 }
218 
219 static int
220 lpt_release_ppbus(device_t dev)
221 {
222 	device_t ppbus = device_get_parent(dev);
223 	struct lpt_data *sc = DEVTOSOFTC(dev);
224 	int error = 0;
225 
226 	if ((error = ppb_release_bus(ppbus, dev)) == 0)
227 		sc->sc_state &= ~HAVEBUS;
228 
229 	return (error);
230 }
231 
232 /*
233  * Internal routine to lptprobe to do port tests of one byte value
234  */
235 static int
236 lpt_port_test(device_t ppbus, u_char data, u_char mask)
237 {
238 	int	temp, timeout;
239 
240 	data = data & mask;
241 	ppb_wdtr(ppbus, data);
242 	timeout = 10000;
243 	do {
244 		DELAY(10);
245 		temp = ppb_rdtr(ppbus) & mask;
246 	}
247 	while (temp != data && --timeout);
248 	lprintf(("out=%x\tin=%x\ttout=%d\n", data, temp, timeout));
249 	return (temp == data);
250 }
251 
252 /*
253  * Probe simplified by replacing multiple loops with a hardcoded
254  * test pattern - 1999/02/08 des@freebsd.org
255  *
256  * New lpt port probe Geoff Rehmet - Rhodes University - 14/2/94
257  * Based partially on Rod Grimes' printer probe
258  *
259  * Logic:
260  *	1) If no port address was given, use the bios detected ports
261  *	   and autodetect what ports the printers are on.
262  *	2) Otherwise, probe the data port at the address given,
263  *	   using the method in Rod Grimes' port probe.
264  *	   (Much code ripped off directly from Rod's probe.)
265  *
266  * Comments from Rod's probe:
267  * Logic:
268  *	1) You should be able to write to and read back the same value
269  *	   to the data port.  Do an alternating zeros, alternating ones,
270  *	   walking zero, and walking one test to check for stuck bits.
271  *
272  *	2) You should be able to write to and read back the same value
273  *	   to the control port lower 5 bits, the upper 3 bits are reserved
274  *	   per the IBM PC technical reference manauls and different boards
275  *	   do different things with them.  Do an alternating zeros, alternating
276  *	   ones, walking zero, and walking one test to check for stuck bits.
277  *
278  *	   Some printers drag the strobe line down when the are powered off
279  * 	   so this bit has been masked out of the control port test.
280  *
281  *	   XXX Some printers may not like a fast pulse on init or strobe, I
282  *	   don't know at this point, if that becomes a problem these bits
283  *	   should be turned off in the mask byte for the control port test.
284  *
285  *	   We are finally left with a mask of 0x14, due to some printers
286  *	   being adamant about holding other bits high ........
287  *
288  *	   Before probing the control port, we write a 0 to the data port -
289  *	   If not, some printers chuck out garbage when the strobe line
290  *	   gets toggled.
291  *
292  *	3) Set the data and control ports to a value of 0
293  *
294  *	This probe routine has been tested on Epson Lx-800, HP LJ3P,
295  *	Epson FX-1170 and C.Itoh 8510RM
296  *	printers.
297  *	Quick exit on fail added.
298  */
299 static int
300 lpt_detect(device_t dev)
301 {
302 	device_t ppbus = device_get_parent(dev);
303 
304 	static u_char	testbyte[18] = {
305 		0x55,			/* alternating zeros */
306 		0xaa,			/* alternating ones */
307 		0xfe, 0xfd, 0xfb, 0xf7,
308 		0xef, 0xdf, 0xbf, 0x7f,	/* walking zero */
309 		0x01, 0x02, 0x04, 0x08,
310 		0x10, 0x20, 0x40, 0x80	/* walking one */
311 	};
312 	int		i, error, status;
313 
314 	status = 1;				/* assume success */
315 
316 	if ((error = lpt_request_ppbus(dev, PPB_DONTWAIT))) {
317 		kprintf(LPT_NAME ": cannot alloc ppbus (%d)!\n", error);
318 		status = 0;
319 		goto end_probe;
320 	}
321 
322 	for (i = 0; i < 18 && status; i++)
323 		if (!lpt_port_test(ppbus, testbyte[i], 0xff)) {
324 			status = 0;
325 			goto end_probe;
326 		}
327 
328 end_probe:
329 	/* write 0's to control and data ports */
330 	ppb_wdtr(ppbus, 0);
331 	ppb_wctr(ppbus, 0);
332 
333 	lpt_release_ppbus(dev);
334 
335 	return (status);
336 }
337 
338 /*
339  * lpt_probe()
340  */
341 static int
342 lpt_probe(device_t dev)
343 {
344 	struct lpt_data *sc;
345 
346 	sc = DEVTOSOFTC(dev);
347 	bzero(sc, sizeof(struct lpt_data));
348 
349 	/*
350 	 * Now, try to detect the printer.
351 	 */
352 	if (!lpt_detect(dev))
353 		return (ENXIO);
354 
355 	device_set_desc(dev, "Printer");
356 
357 	return (0);
358 }
359 
360 static int
361 lpt_attach(device_t dev)
362 {
363 	device_t ppbus = device_get_parent(dev);
364 	struct lpt_data *sc = DEVTOSOFTC(dev);
365 	int zero = 0, unit = device_get_unit(dev);
366 	int error;
367 	uintptr_t irq;
368 
369 	sc->sc_primed = 0;	/* not primed yet */
370 	callout_init(&sc->sc_callout);
371 
372 	if ((error = lpt_request_ppbus(dev, PPB_DONTWAIT))) {
373 		kprintf(LPT_NAME ": cannot alloc ppbus (%d)!\n", error);
374 		return (0);
375 	}
376 
377 	ppb_wctr(ppbus, LPC_NINIT);
378 
379 	/* check if we can use interrupt, should be done by ppc stuff */
380 	lprintf(("oldirq %x\n", sc->sc_irq));
381 
382 	/* retrieve the ppbus irq */
383 	BUS_READ_IVAR(ppbus, dev, PPBUS_IVAR_IRQ, &irq);
384 
385 	if (irq > 0) {
386 		/* declare our interrupt handler */
387 		sc->intr_resource = bus_alloc_legacy_irq_resource(dev, &zero,
388 		    irq, RF_SHAREABLE);
389 	}
390 	if (sc->intr_resource) {
391 		sc->sc_irq = LP_HAS_IRQ | LP_USE_IRQ | LP_ENABLE_IRQ;
392 		device_printf(dev, "Interrupt-driven port\n");
393 	} else {
394 		sc->sc_irq = 0;
395 		device_printf(dev, "Polled port\n");
396 	}
397 	lprintf(("irq %"PRIxPTR" %x\n", irq, sc->sc_irq));
398 
399 	lpt_release_ppbus(dev);
400 
401 	make_dev(&lpt_ops, unit, UID_ROOT, GID_WHEEL,
402 		 0600, LPT_NAME "%d", unit);
403 	make_dev(&lpt_ops, unit | LP_BYPASS, UID_ROOT, GID_WHEEL,
404 		 0600, LPT_NAME "%d.ctl", unit);
405 	return (0);
406 }
407 
408 static void
409 lptout(void *arg)
410 {
411 	device_t dev = (device_t)arg;
412 	struct lpt_data *sc = DEVTOSOFTC(dev);
413 #ifdef LPT_DEBUG
414 	device_t ppbus = device_get_parent(dev);
415 #endif
416 
417 	lprintf(("T %x ", ppb_rstr(ppbus)));
418 	if (sc->sc_state & OPEN) {
419 		sc->sc_backoff++;
420 		if (sc->sc_backoff > hz/LPTOUTMAX)
421 			sc->sc_backoff = sc->sc_backoff > hz/LPTOUTMAX;
422 		callout_reset(&sc->sc_callout, sc->sc_backoff, lptout, dev);
423 	} else {
424 		sc->sc_state &= ~TOUT;
425 	}
426 
427 	if (sc->sc_state & EERROR)
428 		sc->sc_state &= ~EERROR;
429 
430 	/*
431 	 * Avoid possible hangs due to missed interrupts
432 	 */
433 	if (sc->sc_xfercnt) {
434 		lptintr(dev);
435 	} else {
436 		sc->sc_state &= ~OBUSY;
437 		wakeup((caddr_t)dev);
438 	}
439 }
440 
441 /*
442  * lptopen -- reset the printer, then wait until it's selected and not busy.
443  *	If LP_BYPASS flag is selected, then we do not try to select the
444  *	printer -- this is just used for passing ioctls.
445  */
446 
447 static	int
448 lptopen(struct dev_open_args *ap)
449 {
450 	cdev_t dev = ap->a_head.a_dev;
451 	int trys, err;
452 	u_int unit = LPTUNIT(minor(dev));
453 	struct lpt_data *sc = UNITOSOFTC(unit);
454 	device_t lptdev = UNITODEVICE(unit);
455 	device_t ppbus = device_get_parent(lptdev);
456 
457 	if (!sc)
458 		return (ENXIO);
459 
460 	if (sc->sc_state) {
461 		lprintf((LPT_NAME ": still open %x\n", sc->sc_state));
462 		return(EBUSY);
463 	} else
464 		sc->sc_state |= LPTINIT;
465 
466 	sc->sc_flags = LPTFLAGS(minor(dev));
467 
468 	/* Check for open with BYPASS flag set. */
469 	if (sc->sc_flags & LP_BYPASS) {
470 		sc->sc_state = OPEN;
471 		return(0);
472 	}
473 
474 	/* request the ppbus only if we don't have it already */
475 	if ((err = lpt_request_ppbus(lptdev, PPB_WAIT|PPB_INTR)) != 0) {
476 		/* give it a chance to try later */
477 		sc->sc_state = 0;
478 		return (err);
479 	}
480 
481 	crit_enter();
482 	lprintf((LPT_NAME " flags 0x%x\n", sc->sc_flags));
483 
484 	/* set IRQ status according to ENABLE_IRQ flag
485 	 */
486 	if (sc->sc_irq & LP_ENABLE_IRQ)
487 		sc->sc_irq |= LP_USE_IRQ;
488 	else
489 		sc->sc_irq &= ~LP_USE_IRQ;
490 
491 	/* init printer */
492 	if ((sc->sc_flags & LP_NO_PRIME) == 0) {
493 		if((sc->sc_flags & LP_PRIMEOPEN) || sc->sc_primed == 0) {
494 			ppb_wctr(ppbus, 0);
495 			sc->sc_primed++;
496 			DELAY(500);
497 		}
498 	}
499 
500 	ppb_wctr(ppbus, LPC_SEL|LPC_NINIT);
501 
502 	/* wait till ready (printer running diagnostics) */
503 	trys = 0;
504 	do {
505 		/* ran out of waiting for the printer */
506 		if (trys++ >= LPINITRDY*4) {
507 			crit_exit();
508 			sc->sc_state = 0;
509 			lprintf(("status %x\n", ppb_rstr(ppbus)));
510 
511 			lpt_release_ppbus(lptdev);
512 			return (EBUSY);
513 		}
514 
515 		/* wait 1/4 second, give up if we get a signal */
516 		if (tsleep((caddr_t)lptdev, PCATCH, "lptinit", hz/4) !=
517 		    EWOULDBLOCK) {
518 			sc->sc_state = 0;
519 			crit_exit();
520 
521 			lpt_release_ppbus(lptdev);
522 			return (EBUSY);
523 		}
524 
525 		/* is printer online and ready for output */
526 	} while ((ppb_rstr(ppbus) &
527 			(LPS_SEL|LPS_OUT|LPS_NBSY|LPS_NERR)) !=
528 					(LPS_SEL|LPS_NBSY|LPS_NERR));
529 
530 	sc->sc_control = LPC_SEL|LPC_NINIT;
531 	if (sc->sc_flags & LP_AUTOLF)
532 		sc->sc_control |= LPC_AUTOL;
533 
534 	/* enable interrupt if interrupt-driven */
535 	if (sc->sc_irq & LP_USE_IRQ)
536 		sc->sc_control |= LPC_ENA;
537 
538 	ppb_wctr(ppbus, sc->sc_control);
539 
540 	sc->sc_state = OPEN;
541 	sc->sc_inbuf = kmalloc(BUFSIZE, M_LPT, M_WAITOK);
542 	sc->sc_statbuf = kmalloc(BUFSTATSIZE, M_LPT, M_WAITOK);
543 	sc->sc_xfercnt = 0;
544 
545 	crit_exit();
546 
547 	/* release the ppbus */
548 	lpt_release_ppbus(lptdev);
549 
550 	/* only use timeout if using interrupt */
551 	lprintf(("irq %x\n", sc->sc_irq));
552 	if (sc->sc_irq & LP_USE_IRQ) {
553 		sc->sc_state |= TOUT;
554 		sc->sc_backoff = hz / LPTOUTINITIAL;
555 		callout_reset(&sc->sc_callout, sc->sc_backoff, lptout, lptdev);
556 	}
557 
558 	lprintf(("opened.\n"));
559 	return(0);
560 }
561 
562 /*
563  * lptclose -- close the device, free the local line buffer.
564  *
565  * Check for interrupted write call added.
566  */
567 
568 static	int
569 lptclose(struct dev_close_args *ap)
570 {
571 	cdev_t dev = ap->a_head.a_dev;
572 	u_int unit = LPTUNIT(minor(dev));
573 	struct lpt_data *sc = UNITOSOFTC(unit);
574 	device_t lptdev = UNITODEVICE(unit);
575         device_t ppbus = device_get_parent(lptdev);
576 	int err;
577 
578 	if(sc->sc_flags & LP_BYPASS)
579 		goto end_close;
580 
581 	if ((err = lpt_request_ppbus(lptdev, PPB_WAIT|PPB_INTR)) != 0)
582 		return (err);
583 
584 	sc->sc_state &= ~OPEN;
585 
586 	/* if the last write was interrupted, don't complete it */
587 	if((!(sc->sc_state & INTERRUPTED)) && (sc->sc_irq & LP_USE_IRQ)) {
588 		while ((ppb_rstr(ppbus) &
589 		    (LPS_SEL|LPS_OUT|LPS_NBSY|LPS_NERR)) !=
590 		    (LPS_SEL|LPS_NBSY|LPS_NERR) || sc->sc_xfercnt) {
591 			/* wait 1/4 second, give up if we get a signal */
592 			if (tsleep((caddr_t)lptdev, PCATCH,
593 			    "lpclose", hz) != EWOULDBLOCK) {
594 				break;
595 			}
596 		}
597 	}
598 	callout_stop(&sc->sc_callout);
599 	ppb_wctr(ppbus, LPC_NINIT);
600 	kfree(sc->sc_inbuf, M_LPT);
601 	kfree(sc->sc_statbuf, M_LPT);
602 
603 end_close:
604 	/* release the bus anyway
605 	 * unregistration of interrupt forced by release
606 	 */
607 	lpt_release_ppbus(lptdev);
608 
609 	sc->sc_state = 0;
610 	sc->sc_xfercnt = 0;
611 	lprintf(("closed.\n"));
612 	return(0);
613 }
614 
615 /*
616  * lpt_pushbytes()
617  *	Workhorse for actually spinning and writing bytes to printer
618  *	Derived from lpa.c
619  *	Originally by ?
620  *
621  *	This code is only used when we are polling the port
622  */
623 static int
624 lpt_pushbytes(device_t dev)
625 {
626 	struct lpt_data *sc = DEVTOSOFTC(dev);
627 	device_t ppbus = device_get_parent(dev);
628 	int spin, err, tic;
629 	char ch;
630 
631 	lprintf(("p"));
632 	/* loop for every character .. */
633 	while (sc->sc_xfercnt > 0) {
634 		/* printer data */
635 		ch = *(sc->sc_cp);
636 		sc->sc_cp++;
637 		sc->sc_xfercnt--;
638 
639 		/*
640 		 * Wait for printer ready.
641 		 * Loop 20 usecs testing BUSY bit, then sleep
642 		 * for exponentially increasing timeout. (vak)
643 		 */
644 		for (spin = 0; NOT_READY(ppbus) && spin < MAX_SPIN; ++spin)
645 			DELAY(1);	/* XXX delay is NOT this accurate! */
646 		if (spin >= MAX_SPIN) {
647 			tic = 0;
648 			while (NOT_READY(ppbus)) {
649 				/*
650 				 * Now sleep, every cycle a
651 				 * little longer ..
652 				 */
653 				tic = tic + tic + 1;
654 				/*
655 				 * But no more than 10 seconds. (vak)
656 				 */
657 				if (tic > MAX_SLEEP)
658 					tic = MAX_SLEEP;
659 				err = tsleep((caddr_t)dev, 0,
660 					LPT_NAME "poll", tic);
661 				if (err != EWOULDBLOCK) {
662 					return (err);
663 				}
664 			}
665 		}
666 
667 		/* output data */
668 		ppb_wdtr(ppbus, ch);
669 		/* strobe */
670 		ppb_wctr(ppbus, sc->sc_control|LPC_STB);
671 		ppb_wctr(ppbus, sc->sc_control);
672 
673 	}
674 	return(0);
675 }
676 
677 /*
678  * lptread --retrieve printer status in IEEE1284 NIBBLE mode
679  */
680 
681 static int
682 lptread(struct dev_read_args *ap)
683 {
684 	cdev_t dev = ap->a_head.a_dev;
685 	struct uio *uio = ap->a_uio;
686         u_int	unit = LPTUNIT(minor(dev));
687 	struct lpt_data *sc = UNITOSOFTC(unit);
688 	device_t lptdev = UNITODEVICE(unit);
689         device_t ppbus = device_get_parent(lptdev);
690 	int error = 0, len;
691 
692 	if (sc->sc_flags & LP_BYPASS) {
693 		/* we can't do reads in bypass mode */
694 		return (EPERM);
695 	}
696 
697 	if ((error = ppb_1284_negociate(ppbus, PPB_NIBBLE, 0)))
698 		return (error);
699 
700 	/* read data in an other buffer, read/write may be simultaneous */
701 	len = 0;
702 	while (uio->uio_resid) {
703 		error = ppb_1284_read(ppbus, PPB_NIBBLE, sc->sc_statbuf,
704 				      (int)szmin(BUFSTATSIZE, uio->uio_resid),
705 				      &len);
706 		if (error)
707 			goto error;
708 
709 		if (!len)
710 			goto error;		/* no more data */
711 
712 		if ((error = uiomove(sc->sc_statbuf, (size_t)len, uio)))
713 			goto error;
714 	}
715 
716 error:
717 	ppb_1284_terminate(ppbus);
718 	return (error);
719 }
720 
721 /*
722  * lptwrite --copy a line from user space to a local buffer, then call
723  * putc to get the chars moved to the output queue.
724  *
725  * Flagging of interrupted write added.
726  */
727 
728 static	int
729 lptwrite(struct dev_write_args *ap)
730 {
731 	cdev_t dev = ap->a_head.a_dev;
732 	struct uio *uio = ap->a_uio;
733 	unsigned n;
734 	int err;
735         u_int	unit = LPTUNIT(minor(dev));
736 	struct lpt_data *sc = UNITOSOFTC(unit);
737 	device_t lptdev = UNITODEVICE(unit);
738         device_t ppbus = device_get_parent(lptdev);
739 
740 	if(sc->sc_flags & LP_BYPASS) {
741 		/* we can't do writes in bypass mode */
742 		return(EPERM);
743 	}
744 
745 	/* request the ppbus only if we don't have it already */
746 	/* XXX interrupt registration?! */
747 	if ((err = lpt_request_ppbus(lptdev, PPB_WAIT|PPB_INTR)) != 0)
748 		return (err);
749 
750 	/* if interrupts are working, register the handler */
751 	if (sc->sc_irq & LP_USE_IRQ) {
752 		/* register our interrupt handler */
753 		err = BUS_SETUP_INTR(ppbus, lptdev, sc->intr_resource,
754 			       0, lpt_intr, lptdev,
755 			       &sc->intr_cookie, NULL, NULL);
756 		if (err) {
757 			device_printf(lptdev, "handler registration failed, polled mode.\n");
758 			sc->sc_irq &= ~LP_USE_IRQ;
759 		}
760 	}
761 
762 	sc->sc_state &= ~INTERRUPTED;
763 	while ((n = (unsigned)szmin(BUFSIZE, uio->uio_resid)) != 0) {
764 		sc->sc_cp = sc->sc_inbuf;
765 		uiomove(sc->sc_cp, (size_t)n, uio);
766 		sc->sc_xfercnt = n ;
767 
768 		if (sc->sc_irq & LP_ENABLE_EXT) {
769 			/* try any extended mode */
770 			err = ppb_write(ppbus, sc->sc_cp,
771 					sc->sc_xfercnt, 0);
772 			switch (err) {
773 			case 0:
774 				/* if not all data was sent, we could rely
775 				 * on polling for the last bytes */
776 				sc->sc_xfercnt = 0;
777 				break;
778 			case EINTR:
779 				sc->sc_state |= INTERRUPTED;
780 				return(err);
781 			case EINVAL:
782 				/* advanced mode not avail */
783 				log(LOG_NOTICE, LPT_NAME "%d: advanced mode not avail, polling\n", unit);
784 				break;
785 			default:
786 				return(err);
787 			}
788 		} else while ((sc->sc_xfercnt > 0)&&(sc->sc_irq & LP_USE_IRQ)) {
789 			lprintf(("i"));
790 			/* if the printer is ready for a char, */
791 			/* give it one */
792 			if ((sc->sc_state & OBUSY) == 0){
793 				lprintf(("\nC %d. ", sc->sc_xfercnt));
794 				lptintr(lptdev);
795 			}
796 			lprintf(("W "));
797 			if (sc->sc_state & OBUSY)
798 				if ((err = tsleep((caddr_t)lptdev,
799 					 PCATCH, LPT_NAME "write", 0))) {
800 					sc->sc_state |= INTERRUPTED;
801 					return(err);
802 				}
803 		}
804 
805 		/* check to see if we must do a polled write */
806 		if(!(sc->sc_irq & LP_USE_IRQ) && (sc->sc_xfercnt)) {
807 			lprintf(("p"));
808 
809 			err = lpt_pushbytes(lptdev);
810 
811 			if (err)
812 				return(err);
813 		}
814 	}
815 
816 	/* we have not been interrupted, release the ppbus */
817 	lpt_release_ppbus(lptdev);
818 
819 	return(0);
820 }
821 
822 /*
823  * lpt_intr -- handle printer interrupts which occur when the printer is
824  * ready to accept another char.
825  *
826  * do checking for interrupted write call.
827  */
828 
829 static void
830 lpt_intr(void *arg)
831 {
832 	device_t lptdev = (device_t)arg;
833         device_t ppbus = device_get_parent(lptdev);
834 	struct lpt_data *sc = DEVTOSOFTC(lptdev);
835 	int sts = 0;
836 	int i;
837 
838 	/* we must own the bus to use it */
839 	if ((sc->sc_state & HAVEBUS) == 0)
840 		return;
841 
842 	/*
843 	 * Is printer online and ready for output?
844 	 *
845 	 * Avoid falling back to lptout() too quickly.  First spin-loop
846 	 * to see if the printer will become ready ``really soon now''.
847 	 */
848 	for (i = 0; i < 100 &&
849 	     ((sts=ppb_rstr(ppbus)) & RDY_MASK) != LP_READY; i++) ;
850 
851 	if ((sts & RDY_MASK) == LP_READY) {
852 		sc->sc_state = (sc->sc_state | OBUSY) & ~EERROR;
853 		sc->sc_backoff = hz/LPTOUTINITIAL;
854 
855 		if (sc->sc_xfercnt) {
856 			/* send char */
857 			/*lprintf(("%x ", *sc->sc_cp)); */
858 			ppb_wdtr(ppbus, *sc->sc_cp++) ;
859 			ppb_wctr(ppbus, sc->sc_control|LPC_STB);
860 			/* DELAY(X) */
861 			ppb_wctr(ppbus, sc->sc_control);
862 
863 			/* any more data for printer */
864 			if(--(sc->sc_xfercnt) > 0) return;
865 		}
866 
867 		/*
868 		 * No more data waiting for printer.
869 		 * Wakeup is not done if write call was not interrupted.
870 		 */
871 		sc->sc_state &= ~OBUSY;
872 
873 		if(!(sc->sc_state & INTERRUPTED))
874 			wakeup((caddr_t)lptdev);
875 		lprintf(("w "));
876 		return;
877 	} else	{	/* check for error */
878 		if(((sts & (LPS_NERR | LPS_OUT) ) != LPS_NERR) &&
879 				(sc->sc_state & OPEN))
880 			sc->sc_state |= EERROR;
881 		/* lptout() will jump in and try to restart. */
882 	}
883 	lprintf(("sts %x ", sts));
884 }
885 
886 static void
887 lptintr(device_t dev)
888 {
889 	/* call the interrupt at required spl level */
890 	crit_enter();
891 
892 	lpt_intr(dev);
893 
894 	crit_exit();
895 }
896 
897 static	int
898 lptioctl(struct dev_ioctl_args *ap)
899 {
900 	cdev_t dev = ap->a_head.a_dev;
901 	int	error = 0;
902         u_int	unit = LPTUNIT(minor(dev));
903         struct	lpt_data *sc = UNITOSOFTC(unit);
904 	u_char	old_sc_irq;	/* old printer IRQ status */
905 
906 	switch (ap->a_cmd) {
907 	case LPT_IRQ :
908 		if(sc->sc_irq & LP_HAS_IRQ) {
909 			/*
910 			 * NOTE:
911 			 * If the IRQ status is changed,
912 			 * this will only be visible on the
913 			 * next open.
914 			 *
915 			 * If interrupt status changes,
916 			 * this gets syslog'd.
917 			 */
918 			old_sc_irq = sc->sc_irq;
919 			switch(*(int*)ap->a_data) {
920 			case 0:
921 				sc->sc_irq &= (~LP_ENABLE_IRQ);
922 				break;
923 			case 1:
924 				sc->sc_irq &= (~LP_ENABLE_EXT);
925 				sc->sc_irq |= LP_ENABLE_IRQ;
926 				break;
927 			case 2:
928 				/* classic irq based transfer and advanced
929 				 * modes are in conflict
930 				 */
931 				sc->sc_irq &= (~LP_ENABLE_IRQ);
932 				sc->sc_irq |= LP_ENABLE_EXT;
933 				break;
934 			case 3:
935 				sc->sc_irq &= (~LP_ENABLE_EXT);
936 				break;
937 			default:
938 				break;
939 			}
940 
941 			if (old_sc_irq != sc->sc_irq )
942 				log(LOG_NOTICE, LPT_NAME "%d: switched to %s %s mode\n",
943 					unit,
944 					(sc->sc_irq & LP_ENABLE_IRQ)?
945 					"interrupt-driven":"polled",
946 					(sc->sc_irq & LP_ENABLE_EXT)?
947 					"extended":"standard");
948 		} else /* polled port */
949 			error = EOPNOTSUPP;
950 		break;
951 	default:
952 		error = ENODEV;
953 	}
954 
955 	return(error);
956 }
957 
958 /*
959  * Because lpt is a static device that always exists under a ppbus device,
960  * and not scanned by the ppbus device, we need an identify function to
961  * install its device.
962  */
963 static device_method_t lpt_methods[] = {
964 	/* device interface */
965 	DEVMETHOD(device_identify,	bus_generic_identify),
966 	DEVMETHOD(device_probe,		lpt_probe),
967 	DEVMETHOD(device_attach,	lpt_attach),
968 
969 	DEVMETHOD_END
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, NULL, NULL);
979 
980