xref: /netbsd-src/sys/dev/usb/ulpt.c (revision 1b9578b8c2c1f848eeb16dabbfd7d1f0d9fdefbd)
1 /*	$NetBSD: ulpt.c,v 1.86 2011/03/29 07:48:13 mbalmer Exp $	*/
2 /*	$FreeBSD: src/sys/dev/usb/ulpt.c,v 1.24 1999/11/17 22:33:44 n_hibma Exp $	*/
3 
4 /*
5  * Copyright (c) 1998, 2003 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * Printer Class spec: http://www.usb.org/developers/data/devclass/usbprint109.PDF
36  */
37 
38 #include <sys/cdefs.h>
39 __KERNEL_RCSID(0, "$NetBSD: ulpt.c,v 1.86 2011/03/29 07:48:13 mbalmer Exp $");
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/proc.h>
44 #include <sys/kernel.h>
45 #include <sys/fcntl.h>
46 #if defined(__NetBSD__) || defined(__OpenBSD__)
47 #include <sys/device.h>
48 #include <sys/ioctl.h>
49 #elif defined(__FreeBSD__)
50 #include <sys/ioccom.h>
51 #include <sys/module.h>
52 #include <sys/bus.h>
53 #endif
54 #include <sys/uio.h>
55 #include <sys/conf.h>
56 #include <sys/vnode.h>
57 #include <sys/syslog.h>
58 
59 #include <machine/vmparam.h>	/* PAGE_SIZE */
60 
61 #include <dev/usb/usb.h>
62 #include <dev/usb/usbdi.h>
63 #include <dev/usb/usbdi_util.h>
64 #include <dev/usb/usbdevs.h>
65 #include <dev/usb/usb_quirks.h>
66 
67 #define	TIMEOUT		hz*16	/* wait up to 16 seconds for a ready */
68 #define	STEP		hz/4
69 
70 #define	LPTPRI		(PZERO+8)
71 #define	ULPT_BSIZE	PAGE_SIZE
72 
73 #define ULPT_READS_PER_SEC 5
74 /* XXX Why is 10 us a reasonable value? */
75 #define ULPT_READ_TIMO 10
76 
77 #ifdef ULPT_DEBUG
78 #define DPRINTFN(n,x)	if (ulptdebug>=(n)) printf x
79 int	ulptdebug = 0;
80 /*
81  * The strategy for debug levels is:
82  *   1: attach-time operations
83  *   2: open/close/status/reset
84  *   3: read/write basic
85  *   4: read/write details
86  *  10: left over from previous debug code
87  */
88 #else
89 #define DPRINTFN(n,x)
90 #endif
91 
92 #define UR_GET_DEVICE_ID 0
93 #define UR_GET_PORT_STATUS 1
94 #define UR_SOFT_RESET 2
95 
96 #define	LPS_NERR		0x08	/* printer no error */
97 #define	LPS_SELECT		0x10	/* printer selected */
98 #define	LPS_NOPAPER		0x20	/* printer out of paper */
99 #define LPS_INVERT      (LPS_SELECT|LPS_NERR)
100 #define LPS_MASK        (LPS_SELECT|LPS_NERR|LPS_NOPAPER)
101 
102 struct ulpt_softc {
103 	device_t sc_dev;
104 	usbd_device_handle sc_udev;	/* device */
105 	usbd_interface_handle sc_iface;	/* interface */
106 	int sc_ifaceno;
107 
108 	int sc_out;
109 	usbd_pipe_handle sc_out_pipe;	/* bulk out pipe */
110 	usbd_xfer_handle sc_out_xfer;
111 	void *sc_out_buf;
112 
113 	int sc_in;
114 	usbd_pipe_handle sc_in_pipe;	/* bulk in pipe */
115 	usbd_xfer_handle sc_in_xfer;
116 	void *sc_in_buf;
117 
118 	struct callout sc_read_callout;	/* to drain input on write-only opens */
119 	int sc_has_callout;
120 
121 	u_char sc_state;
122 #define	ULPT_OPEN	0x01	/* device is open */
123 #define	ULPT_OBUSY	0x02	/* printer is busy doing output */
124 #define	ULPT_INIT	0x04	/* waiting to initialize for open */
125 	u_char sc_flags;
126 #define	ULPT_NOPRIME	0x40	/* don't prime on open */
127 	u_char sc_laststatus;
128 
129 	int sc_refcnt;
130 	u_char sc_dying;
131 
132 #if defined(__FreeBSD__)
133 	dev_t dev;
134 	dev_t dev_noprime;
135 #endif
136 };
137 
138 #if defined(__NetBSD__)
139 dev_type_open(ulptopen);
140 dev_type_close(ulptclose);
141 dev_type_write(ulptwrite);
142 dev_type_read(ulptread);
143 dev_type_ioctl(ulptioctl);
144 
145 const struct cdevsw ulpt_cdevsw = {
146 	ulptopen, ulptclose, ulptread, ulptwrite, ulptioctl,
147 	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER,
148 };
149 #elif defined(__OpenBSD__)
150 cdev_decl(ulpt);
151 #elif defined(__FreeBSD__)
152 Static d_open_t ulptopen;
153 Static d_close_t ulptclose;
154 Static d_write_t ulptwrite;
155 Static d_ioctl_t ulptioctl;
156 
157 #define ULPT_CDEV_MAJOR 113
158 
159 Static struct cdevsw ulpt_cdevsw = {
160 	/* open */	ulptopen,
161 	/* close */	ulptclose,
162 	/* read */	noread,
163 	/* write */	ulptwrite,
164 	/* ioctl */	ulptioctl,
165 	/* poll */	nopoll,
166 	/* mmap */	nommap,
167 	/* strategy */	nostrategy,
168 	/* name */	"ulpt",
169 	/* maj */	ULPT_CDEV_MAJOR,
170 	/* dump */	nodump,
171 	/* psize */	nopsize,
172 	/* flags */	0,
173 #if !defined(__FreeBSD__) || (__FreeBSD__ < 5)
174 	/* bmaj */	-1
175 #endif
176 };
177 #endif
178 
179 void ulpt_disco(void *);
180 
181 int ulpt_do_write(struct ulpt_softc *, struct uio *uio, int);
182 int ulpt_do_read(struct ulpt_softc *, struct uio *uio, int);
183 int ulpt_status(struct ulpt_softc *);
184 void ulpt_reset(struct ulpt_softc *);
185 int ulpt_statusmsg(u_char, struct ulpt_softc *);
186 void ulpt_read_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
187 		  usbd_status status);
188 void ulpt_tick(void *xsc);
189 
190 #if 0
191 void ieee1284_print_id(char *);
192 #endif
193 
194 #define	ULPTUNIT(s)	(minor(s) & 0x1f)
195 #define	ULPTFLAGS(s)	(minor(s) & 0xe0)
196 
197 
198 int             ulpt_match(device_t, cfdata_t, void *);
199 void            ulpt_attach(device_t, device_t, void *);
200 int             ulpt_detach(device_t, int);
201 int             ulpt_activate(device_t, enum devact);
202 
203 extern struct cfdriver ulpt_cd;
204 
205 CFATTACH_DECL_NEW(ulpt, sizeof(struct ulpt_softc), ulpt_match, ulpt_attach,
206     ulpt_detach, ulpt_activate);
207 
208 int
209 ulpt_match(device_t parent, cfdata_t match, void *aux)
210 {
211 	struct usbif_attach_arg *uaa = aux;
212 	/* XXX Print something useful, or don't. */
213 	DPRINTFN(10,("ulpt_match\n"));
214 
215 	if (uaa->class == UICLASS_PRINTER &&
216 	    uaa->subclass == UISUBCLASS_PRINTER &&
217 	    (uaa->proto == UIPROTO_PRINTER_UNI ||
218 	     uaa->proto == UIPROTO_PRINTER_BI ||
219 	     uaa->proto == UIPROTO_PRINTER_1284))
220 		return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
221 	return (UMATCH_NONE);
222 }
223 
224 void
225 ulpt_attach(device_t parent, device_t self, void *aux)
226 {
227 	struct ulpt_softc *sc = device_private(self);
228 	struct usbif_attach_arg *uaa = aux;
229 	usbd_device_handle dev = uaa->device;
230 	usbd_interface_handle iface = uaa->iface;
231 	usb_interface_descriptor_t *ifcd = usbd_get_interface_descriptor(iface);
232 	const usb_interface_descriptor_t *id;
233 	usbd_status err;
234 	char *devinfop;
235 	usb_endpoint_descriptor_t *ed;
236 	u_int8_t epcount;
237 	int i, altno;
238 	usbd_desc_iter_t iter;
239 
240 	sc->sc_dev = self;
241 
242 	aprint_naive("\n");
243 	aprint_normal("\n");
244 
245 	devinfop = usbd_devinfo_alloc(dev, 0);
246 	aprint_normal_dev(self, "%s, iclass %d/%d\n",
247 	       devinfop, ifcd->bInterfaceClass, ifcd->bInterfaceSubClass);
248 	usbd_devinfo_free(devinfop);
249 
250 	/* Loop through descriptors looking for a bidir mode. */
251 	usb_desc_iter_init(dev, &iter);
252 	for (altno = 0;;) {
253 		id = (const usb_interface_descriptor_t *)usb_desc_iter_next(&iter);
254 		if (!id)
255 			break;
256 		if (id->bDescriptorType == UDESC_INTERFACE &&
257 		    id->bInterfaceNumber == ifcd->bInterfaceNumber) {
258 			if (id->bInterfaceClass == UICLASS_PRINTER &&
259 			    id->bInterfaceSubClass == UISUBCLASS_PRINTER &&
260 			    (id->bInterfaceProtocol == UIPROTO_PRINTER_BI /*||
261 			     id->bInterfaceProtocol == UIPROTO_PRINTER_1284*/))
262 				goto found;
263 			altno++;
264 		}
265 	}
266 	id = ifcd;		/* not found, use original */
267  found:
268 	if (id != ifcd) {
269 		/* Found a new bidir setting */
270 		DPRINTFN(1, ("ulpt_attach: set altno = %d\n", altno));
271 		err = usbd_set_interface(iface, altno);
272 		if (err) {
273 			aprint_error_dev(self,
274 			    "setting alternate interface failed\n");
275 			sc->sc_dying = 1;
276 			return;
277 		}
278 	}
279 
280 	epcount = 0;
281 	(void)usbd_endpoint_count(iface, &epcount);
282 
283 	sc->sc_in = -1;
284 	sc->sc_out = -1;
285 	for (i = 0; i < epcount; i++) {
286 		ed = usbd_interface2endpoint_descriptor(iface, i);
287 		if (ed == NULL) {
288 			aprint_error_dev(self, "couldn't get ep %d\n", i);
289 			return;
290 		}
291 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
292 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
293 			sc->sc_in = ed->bEndpointAddress;
294 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
295 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
296 			sc->sc_out = ed->bEndpointAddress;
297 		}
298 	}
299 	if (sc->sc_out == -1) {
300 		aprint_error_dev(self, "could not find bulk out endpoint\n");
301 		sc->sc_dying = 1;
302 		return;
303 	}
304 
305 	if (usbd_get_quirks(dev)->uq_flags & UQ_BROKEN_BIDIR) {
306 		/* This device doesn't handle reading properly. */
307 		sc->sc_in = -1;
308 	}
309 
310 	aprint_normal_dev(self, "using %s-directional mode\n",
311 	       sc->sc_in >= 0 ? "bi" : "uni");
312 
313 	sc->sc_iface = iface;
314 	sc->sc_ifaceno = id->bInterfaceNumber;
315 	sc->sc_udev = dev;
316 
317 #if 0
318 /*
319  * This code is disabled because for some mysterious reason it causes
320  * printing not to work.  But only sometimes, and mostly with
321  * UHCI and less often with OHCI.  *sigh*
322  */
323 	{
324 	usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
325 	usb_device_request_t req;
326 	int len, alen;
327 
328 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
329 	req.bRequest = UR_GET_DEVICE_ID;
330 	USETW(req.wValue, cd->bConfigurationValue);
331 	USETW2(req.wIndex, id->bInterfaceNumber, id->bAlternateSetting);
332 	USETW(req.wLength, DEVINFOSIZE - 1);
333 	err = usbd_do_request_flags(dev, &req, devinfop, USBD_SHORT_XFER_OK,
334 		  &alen, USBD_DEFAULT_TIMEOUT);
335 	if (err) {
336 		printf("%s: cannot get device id\n", device_xname(sc->sc_dev));
337 	} else if (alen <= 2) {
338 		printf("%s: empty device id, no printer connected?\n",
339 		       device_xname(sc->sc_dev));
340 	} else {
341 		/* devinfop now contains an IEEE-1284 device ID */
342 		len = ((devinfop[0] & 0xff) << 8) | (devinfop[1] & 0xff);
343 		if (len > DEVINFOSIZE - 3)
344 			len = DEVINFOSIZE - 3;
345 		devinfop[len] = 0;
346 		printf("%s: device id <", device_xname(sc->sc_dev));
347 		ieee1284_print_id(devinfop+2);
348 		printf(">\n");
349 	}
350 	}
351 #endif
352 
353 #if defined(__FreeBSD__)
354 	sc->dev = make_dev(&ulpt_cdevsw, device_get_unit(self),
355 		UID_ROOT, GID_OPERATOR, 0644, "ulpt%d", device_get_unit(self));
356 	sc->dev_noprime = make_dev(&ulpt_cdevsw,
357 		device_get_unit(self)|ULPT_NOPRIME,
358 		UID_ROOT, GID_OPERATOR, 0644, "unlpt%d", device_get_unit(self));
359 #endif
360 
361 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
362 			   sc->sc_dev);
363 
364 	DPRINTFN(1, ("ulpt_attach: sc=%p in=%d out=%d\n",
365 		     sc, sc->sc_out, sc->sc_in));
366 
367 	return;
368 }
369 
370 #if defined(__NetBSD__) || defined(__OpenBSD__)
371 int
372 ulpt_activate(device_t self, enum devact act)
373 {
374 	struct ulpt_softc *sc = device_private(self);
375 
376 	switch (act) {
377 	case DVACT_DEACTIVATE:
378 		sc->sc_dying = 1;
379 		return 0;
380 	default:
381 		return EOPNOTSUPP;
382 	}
383 }
384 #endif
385 
386 int
387 ulpt_detach(device_t self, int flags)
388 {
389 	struct ulpt_softc *sc = device_private(self);
390 	int s;
391 #if defined(__NetBSD__) || defined(__OpenBSD__)
392 	int maj, mn;
393 #elif defined(__FreeBSD__)
394 	struct vnode *vp;
395 #endif
396 
397 	DPRINTFN(1, ("ulpt_detach: sc=%p\n", sc));
398 
399 	sc->sc_dying = 1;
400 	if (sc->sc_out_pipe != NULL)
401 		usbd_abort_pipe(sc->sc_out_pipe);
402 	if (sc->sc_in_pipe != NULL)
403 		usbd_abort_pipe(sc->sc_in_pipe);
404 
405 	s = splusb();
406 	if (--sc->sc_refcnt >= 0) {
407 		/* There is noone to wake, aborting the pipe is enough */
408 		/* Wait for processes to go away. */
409 		usb_detach_wait(sc->sc_dev);
410 	}
411 	splx(s);
412 
413 #if defined(__NetBSD__) || defined(__OpenBSD__)
414 	/* locate the major number */
415 #if defined(__NetBSD__)
416 	maj = cdevsw_lookup_major(&ulpt_cdevsw);
417 #elif defined(__OpenBSD__)
418 	for (maj = 0; maj < nchrdev; maj++)
419 		if (cdevsw[maj].d_open == ulptopen)
420 			break;
421 #endif
422 
423 	/* Nuke the vnodes for any open instances (calls close). */
424 	mn = device_unit(self);
425 	vdevgone(maj, mn, mn, VCHR);
426 	vdevgone(maj, mn | ULPT_NOPRIME , mn | ULPT_NOPRIME, VCHR);
427 #elif defined(__FreeBSD__)
428 	vp = SLIST_FIRST(&sc->dev->si_hlist);
429 	if (vp)
430 		VOP_REVOKE(vp, REVOKEALL);
431 	vp = SLIST_FIRST(&sc->dev_noprime->si_hlist);
432 	if (vp)
433 		VOP_REVOKE(vp, REVOKEALL);
434 
435 	destroy_dev(sc->dev);
436 	destroy_dev(sc->dev_noprime);
437 #endif
438 
439 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
440 			   sc->sc_dev);
441 
442 	return (0);
443 }
444 
445 int
446 ulpt_status(struct ulpt_softc *sc)
447 {
448 	usb_device_request_t req;
449 	usbd_status err;
450 	u_char status;
451 
452 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
453 	req.bRequest = UR_GET_PORT_STATUS;
454 	USETW(req.wValue, 0);
455 	USETW(req.wIndex, sc->sc_ifaceno);
456 	USETW(req.wLength, 1);
457 	err = usbd_do_request(sc->sc_udev, &req, &status);
458 	DPRINTFN(2, ("ulpt_status: status=0x%02x err=%d\n", status, err));
459 	if (!err)
460 		return (status);
461 	else
462 		return (0);
463 }
464 
465 void
466 ulpt_reset(struct ulpt_softc *sc)
467 {
468 	usb_device_request_t req;
469 
470 	DPRINTFN(2, ("ulpt_reset\n"));
471 	req.bRequest = UR_SOFT_RESET;
472 	USETW(req.wValue, 0);
473 	USETW(req.wIndex, sc->sc_ifaceno);
474 	USETW(req.wLength, 0);
475 
476 	/*
477 	 * There was a mistake in the USB printer 1.0 spec that gave the
478 	 * request type as UT_WRITE_CLASS_OTHER; it should have been
479 	 * UT_WRITE_CLASS_INTERFACE.  Many printers use the old one,
480 	 * so we try both.
481 	 */
482 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
483 	if (usbd_do_request(sc->sc_udev, &req, 0)) {	/* 1.0 */
484 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
485 		(void)usbd_do_request(sc->sc_udev, &req, 0); /* 1.1 */
486 	}
487 }
488 
489 int ulptusein = 1;
490 
491 /*
492  * Reset the printer, then wait until it's selected and not busy.
493  */
494 int
495 ulptopen(dev_t dev, int flag, int mode, struct lwp *l)
496 {
497 	u_char flags = ULPTFLAGS(dev);
498 	struct ulpt_softc *sc;
499 	usbd_status err;
500 	int spin, error;
501 
502 	sc = device_lookup_private(&ulpt_cd, ULPTUNIT(dev));
503 	if (sc == NULL)
504 		return ENXIO;
505 
506 	if (sc == NULL || sc->sc_iface == NULL || sc->sc_dying)
507 		return (ENXIO);
508 
509 	if (sc->sc_state)
510 		return (EBUSY);
511 
512 	sc->sc_state = ULPT_INIT;
513 	sc->sc_flags = flags;
514 	DPRINTFN(2, ("ulptopen: flags=0x%x\n", (unsigned)flags));
515 
516 #if defined(ULPT_DEBUG) && defined(__FreeBSD__)
517 	/* Ignoring these flags might not be a good idea */
518 	if ((flags & ~ULPT_NOPRIME) != 0)
519 		printf("ulptopen: flags ignored: %b\n", flags,
520 			"\20\3POS_INIT\4POS_ACK\6PRIME_OPEN\7AUTOLF\10BYPASS");
521 #endif
522 
523 
524 	error = 0;
525 	sc->sc_refcnt++;
526 
527 	if ((flags & ULPT_NOPRIME) == 0)
528 		ulpt_reset(sc);
529 
530 	for (spin = 0; (ulpt_status(sc) & LPS_SELECT) == 0; spin += STEP) {
531 		DPRINTFN(2, ("ulpt_open: waiting a while\n"));
532 		if (spin >= TIMEOUT) {
533 			error = EBUSY;
534 			sc->sc_state = 0;
535 			goto done;
536 		}
537 
538 		/* wait 1/4 second, give up if we get a signal */
539 		error = tsleep((void *)sc, LPTPRI | PCATCH, "ulptop", STEP);
540 		if (error != EWOULDBLOCK) {
541 			sc->sc_state = 0;
542 			goto done;
543 		}
544 
545 		if (sc->sc_dying) {
546 			error = ENXIO;
547 			sc->sc_state = 0;
548 			goto done;
549 		}
550 	}
551 
552 	err = usbd_open_pipe(sc->sc_iface, sc->sc_out, 0, &sc->sc_out_pipe);
553 	if (err) {
554 		error = EIO;
555 		goto err0;
556 	}
557 	sc->sc_out_xfer = usbd_alloc_xfer(sc->sc_udev);
558 	if (sc->sc_out_xfer == NULL) {
559 		error = ENOMEM;
560 		goto err1;
561 	}
562 	sc->sc_out_buf = usbd_alloc_buffer(sc->sc_out_xfer, ULPT_BSIZE);
563 	if (sc->sc_out_buf == NULL) {
564 		error = ENOMEM;
565 		goto err2;
566 	}
567 
568 	if (ulptusein && sc->sc_in != -1) {
569 		DPRINTFN(2, ("ulpt_open: opening input pipe %d\n", sc->sc_in));
570 		err = usbd_open_pipe(sc->sc_iface, sc->sc_in,0,&sc->sc_in_pipe);
571 		if (err) {
572 			error = EIO;
573 			goto err2;
574 		}
575 		sc->sc_in_xfer = usbd_alloc_xfer(sc->sc_udev);
576 		if (sc->sc_in_xfer == NULL) {
577 			error = ENOMEM;
578 			goto err3;
579 		}
580 		sc->sc_in_buf = usbd_alloc_buffer(sc->sc_in_xfer, ULPT_BSIZE);
581 		if (sc->sc_in_buf == NULL) {
582 			error = ENOMEM;
583 			goto err4;
584 		}
585 
586 		/* If it's not opened for read then set up a reader. */
587 		if (!(flag & FREAD)) {
588 			DPRINTFN(2, ("ulpt_open: start read callout\n"));
589 			callout_init(&sc->sc_read_callout, 0);
590 			callout_reset(&sc->sc_read_callout, hz/5, ulpt_tick, sc);
591 			sc->sc_has_callout = 1;
592 		}
593 	}
594 
595 	sc->sc_state = ULPT_OPEN;
596 	goto done;
597 
598  err4:
599 	usbd_free_xfer(sc->sc_in_xfer);
600 	sc->sc_in_xfer = NULL;
601  err3:
602 	usbd_close_pipe(sc->sc_in_pipe);
603 	sc->sc_in_pipe = NULL;
604  err2:
605 	usbd_free_xfer(sc->sc_out_xfer);
606 	sc->sc_out_xfer = NULL;
607  err1:
608 	usbd_close_pipe(sc->sc_out_pipe);
609 	sc->sc_out_pipe = NULL;
610  err0:
611 	sc->sc_state = 0;
612 
613  done:
614 	if (--sc->sc_refcnt < 0)
615 		usb_detach_wakeup(sc->sc_dev);
616 
617 	DPRINTFN(2, ("ulptopen: done, error=%d\n", error));
618 	return (error);
619 }
620 
621 /*
622  * XXX Document return value semantics.
623  */
624 int
625 ulpt_statusmsg(u_char status, struct ulpt_softc *sc)
626 {
627 	u_char new;
628 
629 	status = (status ^ LPS_INVERT) & LPS_MASK;
630 	new = status & ~sc->sc_laststatus;
631 	sc->sc_laststatus = status;
632 
633 	if (new & LPS_SELECT)
634 		log(LOG_NOTICE, "%s: offline\n", device_xname(sc->sc_dev));
635 	if (new & LPS_NOPAPER)
636 		log(LOG_NOTICE, "%s: out of paper\n", device_xname(sc->sc_dev));
637 	if (new & LPS_NERR)
638 		log(LOG_NOTICE, "%s: output error\n", device_xname(sc->sc_dev));
639 
640 	return (status);
641 }
642 
643 int
644 ulptclose(dev_t dev, int flag, int mode,
645     struct lwp *l)
646 {
647 	struct ulpt_softc *sc;
648 
649 	sc = device_lookup_private(&ulpt_cd, ULPTUNIT(dev));
650 
651 	if (sc->sc_state != ULPT_OPEN)
652 		/* We are being forced to close before the open completed. */
653 		return (0);
654 
655 	if (sc->sc_has_callout) {
656 		DPRINTFN(2, ("ulptclose: stopping read callout\n"));
657 		callout_stop(&sc->sc_read_callout);
658 		sc->sc_has_callout = 0;
659 	}
660 
661 	if (sc->sc_out_pipe != NULL) {
662 		usbd_abort_pipe(sc->sc_out_pipe);
663 		usbd_close_pipe(sc->sc_out_pipe);
664 		sc->sc_out_pipe = NULL;
665 	}
666 	if (sc->sc_out_xfer != NULL) {
667 		usbd_free_xfer(sc->sc_out_xfer);
668 		sc->sc_out_xfer = NULL;
669 	}
670 
671 	if (sc->sc_in_pipe != NULL) {
672 		usbd_abort_pipe(sc->sc_in_pipe);
673 		usbd_close_pipe(sc->sc_in_pipe);
674 		sc->sc_in_pipe = NULL;
675 	}
676 	if (sc->sc_in_xfer != NULL) {
677 		usbd_free_xfer(sc->sc_in_xfer);
678 		sc->sc_in_xfer = NULL;
679 	}
680 
681 	sc->sc_state = 0;
682 
683 	DPRINTFN(2, ("ulptclose: closed\n"));
684 	return (0);
685 }
686 
687 int
688 ulpt_do_write(struct ulpt_softc *sc, struct uio *uio, int flags)
689 {
690 	u_int32_t n;
691 	int error = 0;
692 	void *bufp;
693 	usbd_xfer_handle xfer;
694 	usbd_status err;
695 
696 	DPRINTFN(3, ("ulptwrite\n"));
697 	xfer = sc->sc_out_xfer;
698 	bufp = sc->sc_out_buf;
699 	while ((n = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
700 		ulpt_statusmsg(ulpt_status(sc), sc);
701 		error = uiomove(bufp, n, uio);
702 		if (error)
703 			break;
704 		DPRINTFN(4, ("ulptwrite: transfer %d bytes\n", n));
705 		err = usbd_bulk_transfer(xfer, sc->sc_out_pipe, USBD_NO_COPY,
706 			  USBD_NO_TIMEOUT, bufp, &n, "ulptwr");
707 		if (err) {
708 			DPRINTFN(3, ("ulptwrite: error=%d\n", err));
709 			error = EIO;
710 			break;
711 		}
712 	}
713 
714 	return (error);
715 }
716 
717 int
718 ulptwrite(dev_t dev, struct uio *uio, int flags)
719 {
720 	struct ulpt_softc *sc;
721 	int error;
722 
723 	sc = device_lookup_private(&ulpt_cd, ULPTUNIT(dev));
724 
725 	if (sc->sc_dying)
726 		return (EIO);
727 
728 	sc->sc_refcnt++;
729 	error = ulpt_do_write(sc, uio, flags);
730 	if (--sc->sc_refcnt < 0)
731 		usb_detach_wakeup(sc->sc_dev);
732 	return (error);
733 }
734 
735 /*
736  * Perform a read operation according to the given uio.
737  * This should respect nonblocking I/O status.
738  *
739  * XXX Doing a short read when more data is available seems to be
740  * problematic.  See
741  * http://www.freebsd.org/cgi/query-pr.cgi?pr=91538&cat= for a fix.
742  * However, this will be unnecessary given a proper fix for the next
743  * problem, and most actual callers read a lot.
744  *
745  * XXX This code should interact properly with select/poll, and that
746  * requires the USB transactions to be queued and function before the
747  * user does a read.  Read will then consume data from a buffer, and
748  * not interact with the device. See ucom.c for an example of how to
749  * do this.
750  */
751 int
752 ulpt_do_read(struct ulpt_softc *sc, struct uio *uio, int flags)
753 {
754 	u_int32_t n, nread, nreq;
755 	int error = 0, nonblocking, timeout;
756 	void *bufp;
757 	usbd_xfer_handle xfer;
758 	usbd_status err = USBD_NORMAL_COMPLETION;
759 
760 	/* XXX Resolve with background reader process.  KASSERT? */
761 	if (sc->sc_in_pipe == NULL)
762 		return EIO;
763 
764 	if (flags & IO_NDELAY)
765 		nonblocking = 1;
766 	else
767 		nonblocking = 0;
768 
769 	if (nonblocking)
770 		timeout = USBD_DEFAULT_TIMEOUT; /* 5 ms */
771 	else
772 		timeout = USBD_NO_TIMEOUT;
773 
774 	DPRINTFN(3, ("ulptread nonblocking=%d uio_reside=%ld timeout=%d\n",
775 		     nonblocking, (u_long)uio->uio_resid, timeout));
776 
777 	xfer = sc->sc_in_xfer;
778 	bufp = sc->sc_in_buf;
779 	nread = 0;
780 	while ((nreq = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
781 		KASSERT(error == 0);
782 		if (error != 0) {
783 			printf("ulptread: pre-switch error %d != 0", error);
784 			goto done;
785 		}
786 
787 		/*
788 		 * XXX Even with the short timeout, this will tsleep,
789 		 * but it should be adequately prompt in practice.
790 		 */
791 		n = nreq;
792 		DPRINTFN(4, ("ulptread: transfer %d bytes, nonblocking=%d timeout=%d\n",
793 			     n, nonblocking, timeout));
794 		err = usbd_bulk_transfer(xfer, sc->sc_in_pipe,
795 			  USBD_NO_COPY | USBD_SHORT_XFER_OK,
796 			  timeout, bufp, &n, "ulptrd");
797 
798 		DPRINTFN(4, ("ulptread: transfer complete nreq %d n %d nread %d err %d\n",
799 			     nreq, n, nread, err));
800 		/*
801 		 * Process "err" return, jumping to done if we set "error".
802 		 */
803 		switch (err) {
804 		case USBD_NORMAL_COMPLETION:
805 			if (n == 0) {
806 				DPRINTFN(3, ("ulptread: NORMAL n==0\n"));
807 			}
808 			break;
809 
810 		case USBD_SHORT_XFER:
811 			/* We said SHORT_XFER_OK, so shouldn't happen. */
812 			DPRINTFN(3, ("ulptread: SHORT n=%d\n", n));
813 			break;
814 
815 		case USBD_TIMEOUT:
816 			if (nonblocking == 0) {
817 				/* XXX Cannot happen; perhaps KASSERT. */
818 				printf("ulptread: timeout in blocking mode\n");
819 				error = EIO;
820 				goto done;
821 			}
822 
823 			DPRINTFN(3, ("ulptread: TIMEOUT n %d nread %d error %d\n",
824 				     n, nread, error));
825 			/*
826 			 * Don't set error until we understand why
827 			 * this happens.
828 			 */
829 			break;
830 
831 		case USBD_INTERRUPTED:
832 			/*
833 			 * The tsleep in usbd_bulk_transfer was
834 			 * interrupted.  Reflect it to the caller so
835 			 * that reading can be interrupted.
836 			 */
837 			error = EINTR;
838 			DPRINTFN(3, ("ulptread: EINTR error %d\n", error));
839 			goto done;
840 			break;
841 
842 		default:
843 			/* Assume all other return codes are really errors. */
844 			error = EIO;
845 			DPRINTFN(3, ("ulptread: n %d err %d error %d\n",
846 				     n, err, error));
847 			goto done;
848 			break;
849 		}
850 		/* XXX KASSERT */
851 		if (error != 0) {
852 			printf("ulptread: post-switch error %d != 0", error);
853 			goto done;
854 		}
855 
856 		if (n > 0) {
857 			/*
858 			 * Record progress to enable later choosing
859 			 * between short reads and EWOULDBLOCK.
860 			 */
861 			nread += n;
862 
863 			/* Copy to userspace, giving up on any error. */
864 			error = uiomove(bufp, n, uio);
865 			if (error != 0)
866 				break;
867 		} else {
868 			/*
869 			 * We read 0 bytes, and therefore are done,
870 			 * even if we aren't in nonblocking mode.
871 			 */
872 			if (error == 0 && nread == 0)
873 				error = EWOULDBLOCK;
874 			DPRINTFN(3, ("ulptread: read 0=>done error %d\n",
875 				     error));
876 			goto done;
877 		}
878 
879 		/*
880 		 * A short transfer indicates no more data will be
881 		 * forthcoming.  Terminate this read regardless of
882 		 * whether we are in nonblocking mode.  XXX Reconsider
883 		 * for blocking mode; maybe we should continue to
884 		 * block, but maybe it just doesn't make senes to do
885 		 * blocking reads from devices like this.
886 		 */
887 		if (err == USBD_SHORT_XFER) {
888 			DPRINTFN(3, ("ulptread: SHORT=>done n %d nread %d err %d error %d\n",
889 				     n, nread, err, error));
890 			break;
891 		}
892 	}
893 
894 done:
895 	DPRINTFN(3, ("ulptread: finished n %d nread %d err %d error %d\n",
896 			     n, nread, err, error));
897 	return (error);
898 }
899 
900 int
901 ulptread(dev_t dev, struct uio *uio, int flags)
902 {
903 	struct ulpt_softc *sc;
904 	int error;
905 
906 	sc = device_lookup_private(&ulpt_cd, ULPTUNIT(dev));
907 
908 	if (sc->sc_dying)
909 		return (EIO);
910 
911 	sc->sc_refcnt++;
912 	error = ulpt_do_read(sc, uio, flags);
913 	if (--sc->sc_refcnt < 0)
914 		usb_detach_wakeup(sc->sc_dev);
915 	return (error);
916 }
917 
918 void
919 ulpt_read_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
920 	     usbd_status status)
921 {
922 	usbd_status err;
923 	u_int32_t n;
924 	usbd_private_handle xsc;
925 	struct ulpt_softc *sc;
926 
927 	usbd_get_xfer_status(xfer, &xsc, NULL, &n, &err);
928 	sc = xsc;
929 
930 	DPRINTFN(4, ("ulpt_read_cb: start sc=%p, err=%d n=%d\n", sc, err, n));
931 
932 #ifdef ULPT_DEBUG
933 	if (!err && n > 0)
934 		DPRINTFN(3, ("ulpt_tick: discarding %d bytes\n", n));
935 #endif
936 	if (!err || err == USBD_TIMEOUT)
937 		callout_reset(&sc->sc_read_callout, hz / ULPT_READS_PER_SEC,
938 			    ulpt_tick, sc);
939 }
940 
941 /*
942  * For devices which are not opened for reading, this function is
943  * called continuously to start read bulk transfers to avoid the
944  * printer overflowing its output buffer.
945  *
946  * XXX This should be adapted for continuous reads to allow select to
947  * work; see do_ulpt_read().
948  */
949 void
950 ulpt_tick(void *xsc)
951 {
952 	struct ulpt_softc *sc = xsc;
953 	usbd_status err;
954 
955 	if (sc == NULL || sc->sc_dying)
956 		return;
957 
958 	usbd_setup_xfer(sc->sc_in_xfer, sc->sc_in_pipe, sc, sc->sc_in_buf,
959 			ULPT_BSIZE, USBD_NO_COPY | USBD_SHORT_XFER_OK,
960 			ULPT_READ_TIMO, ulpt_read_cb);
961 	err = usbd_transfer(sc->sc_in_xfer);
962 	DPRINTFN(3, ("ulpt_tick: sc=%p err=%d\n", sc, err));
963 }
964 
965 int
966 ulptioctl(dev_t dev, u_long cmd, void *data,
967     int flag, struct lwp *l)
968 {
969 	struct ulpt_softc *sc;
970 
971 	sc = device_lookup_private(&ulpt_cd, ULPTUNIT(dev));
972 
973 	switch (cmd) {
974 	case FIONBIO:
975 		return 0;
976 	}
977 
978 	return ENODEV;
979 }
980 
981 #if 0
982 /* XXX This does not belong here. */
983 /*
984  * Print select parts of a IEEE 1284 device ID.
985  */
986 void
987 ieee1284_print_id(char *str)
988 {
989 	char *p, *q;
990 
991 	for (p = str-1; p; p = strchr(p, ';')) {
992 		p++;		/* skip ';' */
993 		if (strncmp(p, "MFG:", 4) == 0 ||
994 		    strncmp(p, "MANUFACTURER:", 14) == 0 ||
995 		    strncmp(p, "MDL:", 4) == 0 ||
996 		    strncmp(p, "MODEL:", 6) == 0) {
997 			q = strchr(p, ';');
998 			if (q)
999 				printf("%.*s", (int)(q - p + 1), p);
1000 		}
1001 	}
1002 }
1003 #endif
1004 
1005 #if defined(__FreeBSD__)
1006 DRIVER_MODULE(ulpt, uhub, ulpt_driver, ulpt_devclass, usbd_driver_load, 0);
1007 #endif
1008