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